YAML Ain't Markup Language (YAML™) 1.0

Working Draft 15 Mar 2003

Latest version:
https://yaml.org/spec/
Editors:
Oren Ben-Kiki, Clark C. Evans, Brian Ingerson

Copyright © 2001-2003 Oren Ben-Kiki, Clark Evans & Brian Ingerson, all rights reserved. This document may be freely copied provided it is not modified.

Status of this Document

This specification is a working draft and reflects consensus reached by the members of the yaml-core mailing list. Any questions regarding this draft should be raised on this list at http://lists.sourceforge.net/lists/listinfo/yaml-core.

With this release of the YAML specificiation, we now encourage development of YAML processors, so that the design of YAML can be validated. The specification is still subject to change; however, such changes will be limited to polish and fixing any logical flaws and bugs.

Therefore, this is "Last Call" for changes; if you have a pet feature now is the very last time that it can be proposed before Release Canaidate status. Changes which would cause "Last Call" YAML streams to be invalid will be seriously considered only if absolutely necessary.

Abstract

YAML™ (rhymes with "camel") is a straightforward machine-parsable data serialization format designed for human readability and interaction with scripting languages such as Perl and Python. YAML is designed for data serialization, formatted dumping, configuration files, log files, Internet messaging and filtering. This specification describes the YAML information model and serialization format. Together with the Unicode standard for characters, it provides all the information necessary to understand YAML Version 1.0 and to construct programs to process YAML information.

Table Of Contents

1 Introduction

YAML Ain't Markup Language, abbreviated YAML, is both a human-readable data serialization format and processing model. This text describes the class of data objects called YAML document streams and partially describes the behavior of computer programs that process them.

YAML document streams encode in a textual form the native data constructs of modern scripting languages. Strings, arrays, hashes, and other user-defined data types are supported. A YAML document stream consists of a sequence of characters, some of which are considered part of the document's content, and others that are used to indicate document structure.

YAML information can be viewed in two primary ways, for machine processing and for human presentation. A YAML processor is a tool for converting information between these complementary views. It is assumed that a YAML processor does its work on behalf of another module, called an application. This specification describes the required behavior of a YAML processor. It describes how a YAML processor must read or write YAML document streams and the information structures it must provide to or obtain from the application.

1.1 Goals

The design goals for YAML are:

  1. YAML documents are very readable by humans.
  2. YAML interacts well with scripting languages.
  3. YAML uses host languages' native data structures.
  4. YAML has a consistent model to support generic tools.
  5. YAML enables stream-based processing.
  6. YAML is expressive and extensible.
  7. YAML is easy to implement.

YAML's initial direction was set by the markup language discussions among SML-DEV members. YAML was also conceived with experience gained from the construction and deployment of Brian Ingerson's Perl module Data::Denter. Since then YAML has matured through the ideas and support it has received from its user community.

1.2 Design

YAML was first conceived as notation for a simple set of primatives, the sequence, the mapping and the scalar, which, when used recursively to form a graph structure, are strong enough for most machine processing needs. By sequence we mean a ordered collection, by mapping we mean an unordered association of unique keys to values, and by scalar we mean a series of unicode characters. These primitives map cleanly to most modern programming languages; the sequence corresponds to a Perl array and a Python list, the mapping corresponds to a Perl hashtable and a Python dictionary. This basis is also formally justified, as both mapping and sequence are mathematical functions with well defined characteristics. With this core model, YAML supports machine processing with a balance of pratical motivation and theory.

To meet the needs of serialization and human presentation, YAML has many syntatical aspects beyond the primitives described above. As a graph is flattened into a tree, ordering is imposed upon mapping keys and an alias mechaism is used to write subsequent occurances of duplicate nodes. To enhance readability, various writing styles are provided for different aesthetic needs. Further, a comment mechanism allows for annotation othogonal to the "content" of a YAML stream. YAML syntax also has other details, such as placement of line breaks and choice of escaping and scalar formats. While these aspects are essential to a human presentation of YAML, they are not needed for machine processing.

This split between machine processing and human presentation creates an inherent tension. While it may be tempting to drive machine processing with comments, key order, styles and other presentation information, this would greatly complicate the definition and operation of generic tools. Although one could argue that their YAML data is sufficently isolated, information is often used in ways unforseen. Therefore, applications should only rely upon the formal definition of YAML's primitives to drive processing. For example, sequences should be used when order is important for machine processing even though mapping key order may be available. Likewise, duplicate keys should never be used, even though a parser may report them without warning. Overall, this distinction is one of intent. Applications which respect the split between human presentation and machine processing will enjoy the ability to use generic tools such as path expressions evaluators, graph transformation languages, or schema validators.

This separation does not prevent YAML processors from providing mechanisms to report or handle presentation aspects. Human readability is a prime directive for YAML. Therefore, a YAML processor may provide a shadow or wrapper mechanism to maintain and provide access to presentation aspects of a YAML text. In this way an application can have influence over how its information will be written to a stream for the best human impact. Since presentation aspects may be the same for a large class of YAML documents, a stylesheet could also be used to provide preferred key ordering, syntax styles, comments, and other presentation oriented instructions.

1.3 Prior Art

YAML integrates and builds upon structures and concepts described by C, Java, Perl, Python, Ruby, RFC0822 (MAIL), RFC1866 (HTML), RFC2045 (MIME), RFC2396 (URI), SAX, SOAP and XML.

YAML's core type system is based on the serialization requirements of Perl, Python and Ruby. YAML directly supports both scalar (string) values and collection ( array, hash) values. Support for common types enables programmers to use their language's native data constructs for YAML manipulation, instead of requiring a special document object model (DOM).

Like XML's SOAP, the YAML serialization supports native graph structures through a rich alias mechanism. Also like SOAP, YAML provides for application-defined types. This allows YAML to serialize rich data structures required for modern distributed computing. YAML provides unique global type names using a namespace mechanism inspired by Java's DNS based package naming convention and XML's URI based namespaces.

YAML's block scoping is similar to Python's. In YAML, the extent of a node is indicated by its column. YAML's literal scalar leverages this by enabling formatted text to be cleanly mixed within an indented structure without troublesome escaping. Further, YAML's block indenting provides for easy inspection of the document's structure.

Motivated by HTML's end-of-line normalization, YAML's folded scalar introduces a unique method of handling white space. In YAML, single line breaks may be folded into a single space, while empty lines represent line break characters. This technique allows for paragraphs to be word-wrapped without affecting the canonical form of the content.

YAML's double quoted scalar uses familar C-style escape sequences. This enables ASCII representation of non-printable or 8-bit (ISO 8859-1) characters such as '\x3B'. 16-bit Unicode and 32-bit (ISO/IEC 10646) characters are supported with escape sequences such as '\u003B' and '\U0000003B'.

The syntax of YAML was motivated by Internet Mail (RFC0822) and remains partially compatible with this standard. Further, YAML borrows the idea of having multiple documents from MIME (RFC2045). YAML's top-level production is a stream of independent documents; ideal for message-based distributed processing systems.

YAML was designed to have an incremental interface that includes both a pull-style input stream and a push-style (SAX-like) output stream interfaces. Together this enables YAML to support the processing of large documents, such as a transaction log, or continuous streams, such as a feed from a production machine.

1.4 Relation to XML

Newcomers to YAML often search for its correlation to the eXtensible Markup Language (XML). While the two languages may actually compete in several application domains, there is no direct correlation between them. YAML is primarily a data serialization language. XML is often used for various types of data serialization but that is not its fundamental design goal.

There are many differences between YAML and XML. XML was designed to be backwards compatible with Standard Generalized Markup Language (SGML) and thus had many design constraints placed on it that YAML does not share. Also XML, inheriting SGML's legacy, is designed to support structured documents, where YAML is more closely targeted at messaging and native data structures. Where XML is a pioneer in many domains, YAML is the result of many lessons from the XML community.

The YAML and XML information models are starkly different. In XML, the primary construct is an attributed tree, where each element has an ordered, named list of children and an unordered mapping of names to strings. In YAML, the primary constructs are sequence (natively stored as an array), mapping (natively stored as a hash) and scalar values (string, integer, floating point). This difference is critical since YAML's model is directly supported by native data structures in most modern programming languages, where XML's model requires mapping conventions, or an alternative programming component (e.g. a document object model).

It should be mentioned that there are ongoing efforts to define standard XML/YAML mappings. This generally requires that a subset of each language be used.

1.5 Terminology

The terminology used to describe YAML is defined in the body of this specification. The terms defined in the following list are used in building those definitions and in describing the actions of a YAML processor:

may
Conformant YAML streams and processors are permitted to but need not behave as described.
should
Conformant YAML streams and processors are encouraged to behave as described, but may do otherwise if a warning message is provided to the user and any deviant behavior requires conscious effort to enable (i.e. a non-default setting).
must
Conformant YAML streams and processors are required to behave as described, otherwise they are in error.
error
A violation of the rules of this specification; results are undefined. Conforming software must detect and report an error and may recover from it.

2 Preview

This section provides a quick glimpse into the expressive power of YAML. It is not expected that the first-time reader grok all of the examples. Rather, these selections are used as motivation for the remainder of the specification.

2.1 Collections

YAML's block collections use indentation for scope and begin each member on its own line. Block sequences indicate each member with a dash (-). Block mappings use a colon to mark each (key: value) pair.

- Mark McGwire
- Sammy Sosa
- Ken Griffey 
A1 Sequence of scalars
(ball players)
hr:  65
avg: 0.278
rbi: 147 
A2 Mapping of scalars to scalars
(player statistics)
american:
   - Boston Red Sox
   - Detroit Tigers
   - New York Yankees
national:
   - New York Mets
   - Chicago Cubs
   - Atlanta Braves 
A3 Mapping of scalars to sequences
(ball clubs in each league)
-
  name: Mark McGwire
  hr:   65
  avg:  0.278
-
  name: Sammy Sosa
  hr:   63
  avg:  0.288 
A4 Sequence of mappings
(players' statistics)

YAML also has in-line flow styles for compact notation. The flow sequence is written as a comma separated list within square brackets. In a similar manner, the flow mapping uses curley braces.

- [ name         , hr , avg   ]
- [ Mark McGwire , 65 , 0.278 ]
- [ Sammy Sosa   , 63 , 0.288 ] 
A5 Sequence of sequences
Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa:   {hr: 63,
               avg: 0.288} 
A6 Mapping of mappings

2.2 Structures

YAML uses three dashes (---) to separate documents within a stream (file or socket). Comment lines begin with the pound sign (#). Repeated nodes are first marked with the ampersand (&) and then referenced with an asterisk (*) thereafter.

---
name: Mark McGwire
hr:   65
avg:  0.278
---
name: Sammy Sosa
hr:   63
avg:  0.288 
B1 Two documents; one stream
(players' statistics)
# Ranking of players by
# 1998 season home runs.
---
- Mark McGwire
- Sammy Sosa
- Ken Griffey

 
B2 Document with leading comment
hr: # 1998 hr ranking
   - Mark McGwire
   - Sammy Sosa
rbi:
   # 1998 rbi ranking
   - Sammy Sosa
   - Ken Griffey 
B3 Single document with two comments
hr:
   - Mark McGwire
   # Following node labeled SS
   - &SS Sammy Sosa
rbi:
   - *SS # Subsequent occurance
   - Ken Griffey 
B4 Node for Sammy Sosa appears
twice in this document

The question mark indicates a complex key. Within a block sequence, mapping pairs can start immediately following the dash.

? # PLAY SCHEDULE
  - Detroit Tigers
  - Chicago Cubs
:
  - 2001-07-23

? [ New York Yankees,
    Atlanta Braves ]
: [ 2001-07-02, 2001-08-12,
    2001-08-14 ] 
B5 Mapping between sequences
invoice: 34843
date   : 2001-01-23
bill-to: Chris Dumars
product:
   - item    : Super Hoop
     quantity: 1
   - item    : Basketball
     quantity: 4
   - item    : Big Shoes
     quantity: 1 
B6 Sequence key shortcut

2.3 Scalars

Scalar values can be written in block form using a literal style (|) where all new lines count. Or they can be written with the folded style (>) for content that can be word wrapped. In the folded style, newlines are treated as a space unless they are part of a blank or indented line.

--- |
  \/|\/|
  / |  |_
 
C1 In literals, newlines are preserved
--- >
    Mark McGwire's
    year was crippled
    by a knee injury. 
C2 In folded, newlines are treated as a space
--- >
 Sammy Sosa completed another
 fine season with great stats.

   63 Home Runs
   0.288 Batting Average

 What a year! 
C3 Newlines preserved for indented and blank lines
name: Mark McGwire
accomplishment: >
   Mark set a major league
   home run record in 1998.
stats: |
   65 Home Runs
   0.278 Batting Average
 
C4 Indentation determines scope

YAML's flow scalars include the plain style (most examples thus far) and quoted styles. The double quoted style provides escape sequences. Single quoted style is useful when escaping is not needed. All flow scalars can span multiple lines; intermediate whitespace is trimmed to a single space.

unicode: "Sosa did fine.\u263A"
control: "\b1998\t1999\t2000\n"
hexesc:  "\x13\x10 is \r\n"

single: '"Howdy!" he cried.'
quoted: ' # not a ''comment''.'
tie-fighter: '|\-*-/|' 
C5 Quoted scalars
plain:
   This unquoted scalar
   spans many lines.
quoted: "So does this
   quoted scalar.\n"

 
C6 Multiline flow scalars

2.4 Type Family

In YAML, plain (unquoted) scalars are given an implicit type depending on the application. YAML's type repository includes integers, floating point values, timestamps, null, boolean, and string values.

canonical: 12345
decimal: +12,345
sexagecimal: 3:25:45
octal: 014
hexadecimal: 0xC
 
D1 Integers
canonical: 1.23015e+3
exponential: 12.3015e+02
sexagecimal: 20:30.15
fixed: 1,230.15
negative infinity: (-inf)
not a number: (NaN) 
D2 Floating point
null: ~
true: y
false: n
string: '12345' 
D3 Miscellaneous
canonical: 2001-12-15T02:59:43.1Z
iso8601:  2001-12-14t21:59:43.10-05:00
spaced:  2001-12-14 21:59:43.10 -05:00
date:   2002-12-14 
D4 Timestamps

Explicit typing is denoted with the bang (!) symbol. Application types should include a domain name and may use the caret (^) to abbreviate subsequent types.

---
not-date: !str 2002-04-28
picture: !binary#base64 |
 R0lGODlhDAAMAIQAAP//9/X
 17unp5WZmZgAAAOfn515eXv
 Pz7Y6OjuDg4J+fn5OTk6enp
 56enmleECcgggoBADs=

hmm: !somewhere.com,2002/type |
 family above is shorthand for
 taguri:somewhere.com,2002:type
 
D5 Various explicit families
--- !clarkevans.com,2002/graph/^shape
  # !clarkevans.com,2002/graph/circle
- !^circle
  center: &ORIGIN {x: 73, y: 129}
  radius: 7
- !^line
  start: *ORIGIN
  finish: { x: 89, y: 102 }
- !^text
  start: *ORIGIN
  color: 0xFFEEBB
  value: Pretty vector drawing. 
D6 Application specific family

2.5 Full Length Example

Below are two full-length examples of YAML. On the left is a sample invoice; on the right is a sample log file.

--- !clarkevans.com,2002/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments:
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338. 
E1 Invoice
---
Time: 2001-11-23 15:01:42 -05:00
User: ed
Warning:
  This is an error message
  for the log file
---
Time: 2001-11-23 15:02:31 -05:00
User: ed
Warning:
  A slightly different error
  message.
---
Date: 2001-11-23 15:03:17 -05:00
User: ed
Fatal:
  Unknown variable "bar"
Stack:
  - file: TopClass.py
    line: 23
    code: |
      x = MoreObject("345\n")
  - file: MoreClass.py
    line: 58
    code: |-
      foo = bar


 
E2 Log file

3 Syntax

Following are the BNF productions defining the syntax of YAML streams.

3.1 Characters

Characters are the basis for a YAML stream. Below is a general definition of a character followed by several characters that have specific meaning in particular contexts.

3.1.1 Character Set

YAML streams use a subset of the Unicode character set. A YAML parser must accept all printable ASCII characters, the space, tab, line break, and all Unicode characters beyond 0x9F. A YAML emitter must only produce those characters accepted by the parser, but should also escape all non-printable Unicode characters if a character table is readily available.

[001]
c-printable ::=
    #x9 | #xA | #xD
  | [#x20-#x7E] | #x85
  | [#xA0-#xD7FF]
  | [#xE000-#xFFFD]
  | [#x10000-#x10FFFF] 
/* characters as defined by the Unicode standard, excluding most control characters and the surrogate blocks */

The range above explicitly excludes the surrogate block [#xD800-#xDFFF], DEL 0x7F, the C0 control block [#x0-#x1F], the C1 control block [#x80-#x9F], #xFFFE and #xFFFF. Note that in UTF-16, characters above #xFFFF are represented with a surrogate pair. DEL and characters in the C0 and C1 control block may be represented in a YAML stream using escape sequences.

3.1.2 Encoding

A YAML parser is required to support the UTF-32, UTF-16 and UTF-8 character encodings. If an input stream does not begin with a byte order mark, the encoding shall be UTF-8. Otherwise the encoding shall be UTF-32 (LE or BE), UTF-16 (LE or BE) or UTF-8, as signaled by the byte order mark. Note that as YAML files may only contain printable characters, this does not raise any ambiguities. For more information about the byte order mark and the Unicode character encoding schemes see the Unicode FAQ.

[002]
c-byte-order-mark ::= #xFEFF 
/* the Unicode ZERO WIDTH NON-BREAKING SPACE character used to mark a UTF-32 or UTF-16 stream and determine byte ordering */

3.1.3 Indicators

Indicators are special characters that are used to describe the structure of a YAML document.

[003]
c-sequence-entry ::= '-' 
/* indicates a sequence entry */
[004]
c-mapping-entry ::= ':' 
/* separates a key from its value */
[005]
c-sequence-start ::= '[' 
/* starts a flow sequence collection */
[006]
c-sequence-end ::= ']' 
/* ends a flow sequence collection */
[007]
c-mapping-start ::= '{' 
/* starts a flow mapping collection */
[008]
c-mapping-end ::= '}' 
/* ends a flow mapping collection */
[009]
c-collect-entry ::= ',' 
/* separates flow collection entries */
[010]
c-top-key ::= '?' 
/* indicates a complex key */
[011]
c-alias ::= '*' 
/* indicates an alias node */
[012]
c-anchor ::= '&' 
/* indicates an anchor-name property */
[013]
c-transfer ::= '!' 
/* indicates a transfer method property */
[014]
c-literal ::= '|' 
/* indicates a literal scalar */
[015]
c-folded ::= '>' 
/* indicates a folded scalar */
[016]
c-single-quote ::= ''' 
/* indicates a single quoted scalar */
[017]
c-double-quote ::= '"' 
/* indicates a double quoted scalar */
[018]
c-throwaway ::= '#' 
/* indicates a throwaway comment */
[019]
c-directive ::= '%' 
/* indicates a directive */
[020]
c-reserved ::= '@' | '`' 
/* reserved for future use */

3.1.4 Line Breaks

The Unicode standard defines several line break characters. These line breaks can be grouped into two categories. Specific line breaks have well-defined semantics for breaking text into lines and paragraphs. The semantics of generic line break characters is not defined beyond "ending a line".

[021]
b-line-feed ::= #xA 
/* ASCII line feed (LF) */
[022]
b-carriage-return ::= #xD 
/* ASCII carriage return (CR) */
[023]
b-next-line ::= #x85 
/* Unicode next line (NEL) */
[024]
b-line-separator ::= #x2028 
/* Unicode line separator (LS) */
[025]
b-paragraph-separator ::= #x2029 
/* Unicode paragraph separator (PS) */
[026]
b-char ::=
    b-line-feed
  | b-carriage-return
  | b-next-line
  | b-line-separator
  | b-paragraph-separator 
/* line break characters */
[027]
b-generic ::=
    ( b-carriage-return
      b-line-feed )greedy
  | b-carriage-return
  | b-line-feed
  | b-next-line 
/* line break with non-specific semantics */
[028]
b-specific ::=
    b-line-separator
  | b-paragraph-separator 
/* line break with specific semantics */
[029]
b-any ::=
  b-generic | b-specific 
/* any non-content line break */

Outside scalar text content, YAML allows any line break to be used to terminate lines, and in most cases also allows such line breaks to be preceded by trailing comment characters. On output, a YAML emitter is free to emit such line breaks using whatever convention is most appropriate. An emitter should avoid emitting trailing line spaces.

3.1.5 Miscellaneous

This section includes several common character range definitions.

[030]
nb-char ::= c-printable - b-char 
/* characters valid in a line */
[031]
s-char ::= #x9 | #x20 
/* white space valid in a line */
[032]
ns-char ::= nb-char - s-char 
/* non-space characters valid in a line */
[033]
ns-ascii-letter ::=
  [#x41-#x5A] | [#x61-#x7A] 
/* ASCII letters, A-Z or a-z */
[034]
ns-decimal-digit ::= [#x30-#x39] 
/* 0-9 */
[035]
ns-hex-digit ::=
    ns-decimal-digit
  | [#x41-#x46] | [#x61-#x66] 
/* 0-9, A-F or a-f */
[036]
ns-word-char ::=
    ns-decimal-digit
  | ns-ascii-letter | '-' 
/* characters valid in a word */

3.2 Space Processing

YAML streams use lines and spaces to convey structure. This requires special processing rules for white space (space and tab).

3.2.1 Indentation

In a YAML text representation, structure is determined from indentation, where indentation is defined as a line break character followed by zero or more space characters.

Tab characters are not allowed in indentation. Since different systems treat tabs differently, portability problems are a concern. Therefore, YAML's tab policy is conservative; they are not allowed. Note that most modern editors may be configured so that pressing the tab key results in the insertion of an appropriate number of spaces.

With one notable exception, a node must be more indented than its parent node. All sibling nodes must use the exact same indentation level. However the content of each such node may be indented independently.

The indentation level is used exclusively to delineate structure. Indentation characters are otherwise ignored. In particular, they are never taken to be a part of the the serialized text.

[037]
i-spaces(n) ::= #x20 x n 
/* specific level of indentation */
[038]
i-spaces(<n) ::= i-spaces(m) 
/* for some specific m such that m < n */
[039]
i-spaces(<=n) ::= i-spaces(m) 
/* for some specific m such that m <= n */

Since the YAML stream depends upon indentation level to delineate blocks, additional productions are a function of an integer, based on the i-spaces(n), i-spaces(<n) and i-spaces(<=n) productions above. In some cases the notation production(any) is used; it is a shorthand for "production(n) for some specific of n such that n >= 0".

The '-' sequence entry indicator is perceived by people to be part of the indentation. Hence the indentation rules are slightly more flexible when dealing with this indicator. First, a block sequence need not be indented relative to its parent node, unless that node is a block sequence entry. For example:

a key in a mapping at indentation level 0:
# The value for this key is a block sequence.
- This sequence is also at indentation level 0.
-   Another entry in the sequence.
- # The value of this entry is a nested sequence.
 - This nested sequence must be
  indented at least to level 1.
 - Another entry in the nested sequence.
- Last entry in block sequence at indentation level 0.
second key in mapping: at indentation level 0. 

In addition, in the special case when the value of a sequence entry is a block collection, and neither the nested block collection nor its first entry have any properties specified (type family or anchor), then this first entry may be specified in the same line as the '-' indicator of the containing sequence entry. In this case both the '-' and any following spaces are counted as part of the indentation. For example:

- This sequence is not indented.
-   map-in-seq: further indented by four.
    this key: is also further indented by four.
-  - seq-in-seq; further indented by three.
   -    second entry in nested sequence.
- Last entry in top sequence. 

3.2.2 Throwaway comments

Throwaway comments have no effect whatsoever on the data serialized in the stream. Their usual purpose is to communicate between the human maintainers of the file. A typical example is comments in a configuration file.

A throwaway comment always spans to the end of a line. It consists of white spaces, optionally followed by a '#' indicator and arbitrary comment characters to the end of the line.

Outside text content, empty lines or lines containing only white space are taken to be implicit throwaway comment lines. Lines containing indentation followed by '#' and comment characters are taken to be explicit throwaway comment lines.

A throwaway comment may appear before a document node or following any node. It may not appear inside a scalar node, but may precede or follow it.

[040]
c-nb-throwaway-comment ::=
  c-throwaway nb-char
/* comment trailing a line */
[041]
l-comment(n) ::=
    l-empty-comment(n)
  | l-text-comment(n) 
/* types of comment lines */
[042]
l-empty-comment(n) ::=
  i-spaces(<=n) b-any 
/* empty throwaway comment line */
[043]
l-text-comment(n) ::=
  i-spaces(<n)
  c-nb-throwaway-comment
  b-any 
/* explicit throwaway comment line */
[044]
s-b-trailing-comment ::=
  ( s-char+
    c-nb-throwaway-comment? )?
  b-any 
/* trailing non-content spaces, comment and line break */
###The first tree lines of this stream

## are comments (the second one is empty).
this: |   # Comments may trail block indicators.
    contains three lines of text.
    The third one starts with a
    # character. This isn't a comment.

# The last three lines of this stream
# are comments (the first line is empty). 

3.3 YAML Stream

A sequence of bytes is a YAML stream if, taken as a whole, it complies with the following production. Note that an empty stream is a valid YAML stream containing no documents.

Encoding is assumed to be UTF-8 unless explicitly specified by including a byte order mark as the first character of the stream. While a byte order mark may also appear before additional document headers, the same encoding must be used for all documents contained in a YAML stream.

[045]
c-l-yaml-stream ::=
  ( c-l-before-document
    l-l-implicit-document
    l-l-after-document? )?
  ( c-l-before-document
    l-l-explicit-document
    l-l-after-document? )* 
/* YAML document stream */
[046]
c-l-before-document ::=
  c-byte-order-mark?
  #l-comment(any)
/* comments before actual document starts */
[047]
l-l-implicit-document ::=
    l-l-blk-collection(any)
  | l-l-top-flow-collect-node(any) 
/* first document with an implicit header line */
[048]
l-l-explicit-document ::=
  ns-ns-document-header
  ( s-l-top-scalar-node(any)
  | s-l-top-collect-node(any)
/* stream document with an explicit header */

3.3.1 Document

A YAML stream may contain several independent YAML documents. A document header line is used to start a new document. This line must start with a document separator: '---' followed by a line break or a sequence of space characters. If no explicit header line is specified at the start of the stream, the parser should behave as if a header line containing an unadorned '---' was specified.

When YAML is used as the format for a communication stream, it is useful to be able to indicate the end of a document independent of starting the next one. Without such a marker, the YAML processor reading the stream would be forced to wait for the header of the next document (that may be long time in coming) in order to detect the end of the previous document.

To support this scenario, a YAML document may be terminated by a '...' line. Nothing but throwaway comments may appear between this line and the (mandatory) header line of the following document.

[049]
ns-ns-document-header ::=
  ns-ns-document-start
  ( s-char+ c-ns-directive )* 
/* YAML document header */
[050]
ns-ns-document-start ::= '-' '-' '-' 
/* YAML document start indicator */
[051]
l-l-after-document ::=
  ns-ns-document-end b-any
  l-comment(any)
/* YAML document trailer */
[052]
ns-ns-document-end ::= '.' '.' '.' 
/* YAML document end indicator */
--- >
This YAML stream contains a single text value.
The next stream is a log file - a sequence of
log entries. Adding an entry to the log is a
simple matter of appending it at the end. 
---
at: 2001-08-12 09:25:00.00 Z
type: GET
HTTP: '1.0'
url: '/index.html'
---
at: 2001-08-12 09:25:10.00 Z
type: GET
HTTP: '1.0'
url: '/toc.html' 
# This stream is an example of a top-level mapping.
invoice : 34843
date    : 2001-01-23
total   : 4443.52 
# A one-line alternative syntax for the above document.
[ invoice: 34843, date: 2001-01-23, total: 4443.52 ] 
# The following is a stream of three documents. The first is an empty
# mapping, the second an empty sequence, and the last an empty string.
--- {}
--- [ ]
--- '' 
# A communication channel based on a YAML stream.
---
sent at: 2002-06-06 11:46:25.10 Z
payload: Whatever
# Receiver can process this as soon as the following is sent:
...
# Even if the next message is sent long after:
---
sent at: 2002-06-06 12:05:53.47 Z
payload: Whatever
... 

3.3.2 Directive

Directives are instructions to the YAML parser. Like throwaway comments, directives are not reflected in the data serialized in the stream. Directives apply to a single document. It is an error for the same directive to be specified more than once for the same document.

[053]
c-ns-directive ::=
  c-directive ns-ns-directive-name
  c-mapping-entry ns-ns-directive-value 
/* document directive */
[054]
ns-ns-directive-name ::=
  ( ns-char - c-mapping-entry )+ 
/* document directive name */
[055]
ns-ns-directive-value ::= ns-char
/* document directive value */

This version of YAML defines a single directive, %YAML. Additional directives may be added in future versions of YAML. A parser should ignore unknown directives with an appropriate warning. There is no provision for specifying private directives. This is intentional.

The %YAML directive specifies the version of YAML the document adheres to. This specification defines version 1.0.

A version 1.0 parser should accept documents with an explicit %YAML:1.0 directive, as well as documents lacking a %YAML directive. Documents with a directive specifying a higher minor version (e.g. %YAML:1.1) should be processed with an appropriate warning. Documents with a directive specifying a higher major version (e.g. %YAML:2.0) should be rejected with an appropriate error message.

3.3.3 Text Node

A text node begins at a particular level of indentation, n, and its content is indented at some level >n. A text node can be a collection (mapping or sequence), a scalar (block or flow) or an alias.

A YAML document is a normal node. However a document can't be an alias (there is nothing it may refer to). Also if the header line is omitted the first document must be a collection.

[056]
s-l-top-value-node(n) ::=
    s-l-top-alias-node
  | s-l-top-collect-node(n)
  | s-l-top-scalar-node(n) 
/* value node outside flow collection */
[057]
ns-ns-flow-value-node(n) ::=
    ns-ns-alias
  | c-c-flow-collect-node(n)
  | ns-ns-flow-scalar-value-node(n) 
/* value node inside flow collection */
[058]
ns-s-top-key-node(n) ::=
    ( c-top-key s-l-top-value-node(>n)
      i-spaces(n) )
  | ( ns-ns-flow-key-node(n) s-char* ) 
/* key node outside flow collection */
[059]
ns-ns-flow-key-node(n) ::=
    ns-ns-alias
  | c-c-flow-collect-node(n)
  | ns-ns-flow-scalar-key-node(n) 
/* key node inside flow collection */
[060]
s-l-top-alias-node ::=
  s-char ns-ns-alias
  s-b-trailing-comment
  l-comment(any)
/* alias node outside flow collection */
[061]
l-l-top-flow-collect-node(n) ::=
  i-spaces(n)
  c-c-flow-collect-node(n)
  s-b-trailing-comment
  l-comment(any)
/* top-level (document) flow collection node */
[062]
s-l-top-collect-node(n) ::=
    s-l-blk-collect-node(n)
  | ( s-s-required(n)
      c-c-flow-collect-node(n)
      s-b-trailing-comment
      l-comment(any)* ) 
/* collection node outside flow collection */
[063]
s-l-blk-collect-node(n) ::=
  ( s-char+ c-ns-collect-properties )?
  s-b-trailing-comment
  l-comment(any)*
  l-l-blk-collection(n) 
/* collection node in block style */
[064]
c-c-flow-collect-node(n) ::=
  ( c-ns-collect-properties s-char+ )?
  c-c-flow-collection(n) 
/* collection node inside flow collection */
[065]
s-l-top-scalar-node(n) ::=
    s-l-blk-scalar-node(n)
  | ( s-s-required(n)
      ns-ns-top-scalar-value-node(n)
      s-b-trailing-comment
      l-comment(any)* ) 
/* scalar node outside flow collection */
[066]
s-l-blk-scalar-node(n) ::=
  ( s-char+ c-ns-scalar-properties )?
  s-char+ c-l-blk-scalar(n) 
/* scalar node in block style */
[067]
ns-ns-top-scalar-value-node(n) ::=
  ( c-ns-scalar-properties s-char+ )?
  ns-ns-top-scalar-value(n) 
/* scalar node using flow style outside flow collection */
[068]
ns-ns-flow-scalar-value-node(n) ::=
  ( c-ns-scalar-properties s-char+ )?
  ns-ns-flow-scalar-value(n) 
/* scalar value node inside flow collection */
[069]
ns-ns-flow-scalar-key-node(n) ::=
  ( c-ns-scalar-properties s-char+ )?
  ns-ns-flow-scalar-key(n) 
/* scalar key node inside flow collection */

3.3.4 Node Property

Each text node may have anchor and transfer method properties. These properties are specified in a properties list appearing before the node value itself. For a top-level node (a document), the properties appear in the document header line, following the directives (if any). It is an error for the same property to be specified more than once for the same node.

[070]
c-ns-collect-properties ::=
    ( c-ns-collect-transfer
      ( s-char+ c-ns-anchor-property )? )
  | ( c-ns-anchor-property
      ( s-char+ c-ns-collect-transfer )? ) 
/* collection properties list */
[071]
c-ns-scalar-properties ::=
    ( c-ns-scalar-transfer
      ( s-char+ c-ns-anchor-property )? )
  | ( c-ns-anchor-property
      ( s-char+ c-ns-scalar-transfer )? ) 
/* scalar properties list */

3.3.5 Transfer Method

The transfer method property specifies how to load the associated node. It includes the type family for the node and, for global scalar type families, an optional specific format used, separated by a '#' character.

Like throwaway comments and directives, formats are not reflected in the data serialized in the stream. In contrast, the type family is considered to be part of this data.

Explicit/Implicit

By providing an explicit transfer property to a node, implicit typing is prevented. However, an explicit empty transfer method property can be used to force implicit typing to be applied to a node. If either an empty explicit format or no explicit format are given, the loader automatically detects the format.

implicit integer type family: 12
also implicit integer family: ! "12"
explicit integer, implicit format: !int 12
also implicit format: !int# 0x12
explicit format: !int#dec 0x12 
Shorthands

YAML makes use of the taguri: scheme for defining URIs for its global type families and the x-private: scheme for its private type families. While these schemes provide the necessary semantics for identifying type families, they are rather verbose.

To increase readability, YAML does not use the full URI notation in the stream. Instead, it provides several shorthand notations for different groups of type family URIs. A parser may choose not to expand shorthand type family names to URIs. However, in such a case the parser must still perform escaping to ensure a single unique representation of each type family name.

  • If the type family begins with a '!' character, it is taken to be a private type family whose URI is under the x-private: scheme. URI fragments are allowed but their semantics is completely up to the semantics of the private type. In particular, they may or may not indicate a format.

    # Both examples below make use of the 'x-private:ball'
    # type family URI, but with different semantics.
    ---
    pool: !!ball { number: 8 }
    ---
    bearing: !!ball { material: steel } 
  • If the type family contains no ':' and no '/' characters it is assumed to be defined under the yaml.org domain. This domain is used to define the core and universal YAML data types.

    # The URI is 'taguri:yaml.org,2002:str'
    - !str a Unicode string 
  • Otherwise, if the type family begins with a single word, followed by a '/' character, it is assumed to belong to a sub-domain of yaml.org. Each domain vocabulary.yaml.org will include all globally unique types of the vocabulary that aren't covered by the set of universal types. Each vocabulary would contain a set of related types, for example types specific to a particular programming language.

    Globally unique types for each language include any built-in types and any standard library types. For languages such as Java and C#, all type names based on reverse DNS strings are globally unique. For languages such as Perl, that has a central authority (CPAN) for managing the global namespace, all the types sanctioned by the central authority are globally unique. The list of supported languages and their types is maintained as part of the YAML type repository.

    # The URI is 'taguri:perl.yaml.org,2002:Text::Tabs'
    - !perl/Text::Tabs {} 
  • Otherwise, the type family must begin with a domain name and a date (separated by a ',' character), followed by a '/' character. In this case it is taken to be defined under the specified domain and date.

    # The URI is 'taguri:clarkevans.com,2003-02:timesheet'
    - !clarkevans.com,2003-02/timesheet 
  • Type families defined in the yaml.org domain or any of its sub-domains must be defined using the appropriate specialized shorthand rather than using the generic domain syntax. This ensures each type family has a unique representation as a shorthand, in addition to having a unique representation as a URI.

Escaping

YAML allows non-printable Unicode characters to be used in a transfer method using escape sequences.

# The following values have the same type family.
- !domain.tld,2002/type\x30 value
- !domain.tld,2002/type0 value 
Expanding

Sometimes it may be helpful for a YAML type family or transfer method to be expanded to a full URI. A YAML processor may provide a mechanism to perform such expansion. Since URIs support a limited ASCII-based character set, this expansion requires all characters outside this set to be encoded in UTF-8 and the resulting bytes to be encoded using % notation.

When an explicit % character appears in a transfer method, it is passed to the URI form unchanged, allowing explicit % escapes to be used in the transfer method where necessary. It is an error for a transfer method not to have a valid expanded URI format (e.g., contain an invalid explicit % escape sequence).

# The following are different as far as YAML is concerned.
- !domain.tld,2002/type%30 value
- !domain.tld,2002/type0 value 
Prefixing

YAML provides convenient shorthand for the common case where a node and (most of) its descendents have global types families whose shorthand forms share a common prefix. For this case, YAML allows using the '^' character to separate the ancestor node's type family into a prefix and a suffix. The parser does not consider the separator to be part of type family name.

When the parser encounters a descendant node whose type family name begins with '^', it appends the ancestor node's prefix to it. Again the '^' character is not taken to be part of the name.

It is possible for a descendant node to establish a different prefix. In this case the node may not make use of its ancestor's node prefix. It must specify a full type family name, separated into a prefix and suffix as above.

It is an error for a node's type family name to begin with '^' unless it has an ancestor node establishing a prefix. However, a node may establish a prefix even if none of its descendents make use of it.

Note that the type prefix mechanism is purely syntactical and does not imply any additional semantics. In particular, the prefix must not be assumed to be an identifier for anything.

# 'taguri:domain.tld,2002:invoice' is some type family.
invoice: !domain.tld,2002/^invoice
  # 'seq' is shorthand for 'taguri:yaml.org,2002:seq'.
  # This does not effect '^customer' below
  # because it is does not specify a prefix.
  customers: !seq
    # '^customer' is shorthand for the full notation
    # '!domain.tld,2002/customer' that stands for the
    # URI 'taguri:domain.tld,2002:customer'.
    - !^customer
      given : Chris
      family : Dumars 
[072]
c-prefix ::= '^' 
/* separates prefix from type */
[073]
c-format ::= '#' 
/* separates type from format */
[074]
ns-transfer-char ::=
    ns-esc-sequence
  | ( ns-char - c-escape - c-format
/* characters valid in a transfer metrhod */
[075]
ns-mundane-transfer-char ::=
  ns-transfer-char - ':' - '/' 
/* non-magical URI character */
[076]
c-ns-collect-transfer ::=
  c-transfer
  ( /* empty (implicit) */
  | ns-ns-transfer-family
  | ( prefix-of-above?
      c-prefix
      suffix-of-above ) ) 
/* collection transfer method (no format) */
[077]
c-ns-scalar-transfer ::=
  c-transfer
  ( /* empty (implicit) */
  | ns-ns-transfer-family
  | ns-ns-transfer-format
  | ( prefix-of-above?
      c-prefix
      suffix-of-above ) ) 
/* scalar transfer method (with format) */
[078]
ns-ns-transfer-family ::=
  c-ns-private-family
  ns-ns-global-family 
/* family transfer method (no format) */
[079]
ns-ns-transfer-format ::=
  ns-ns-transfer-family
  c-format ns-ns-format 
/* transfer method (with format) */
[080]
c-ns-private-family ::=
  c-transfer ns-transfer-char
/* private type names */
[081]
ns-ns-global-family ::=
    ns-ns-core-family
  | ns-ns-vocabulary-family
  | ns-ns-domain-family 
/* global type names */
[082]
ns-ns-format ::= ns-transfer-char
/* format of a scalar */
[083]
ns-ns-core-family ::=
  ( ns-mundane-transfer-char
  - c-transfer )
  ns-mundane-transfer-char
/* shorthand for taguri:
yaml.org,2002:type names */
[084]
ns-ns-vocabulary-family ::=
  ns-word-char+ '/' ns-transfer-char
/* shorthand for taguri:vocabulary
.yaml.org,2002:type names */
[085]
ns-ns-domain-family ::=
  ns-word-char+
  ( '.' ns-word-char )
  ',' ns-ns-domain-year
  ( '-' ns-ns-domain-day-month
    ( '-' ns-ns-domain-day-month )? )?
  '/' ns-transfer-char
/* shorthand for taguri:domain,date:type names */
[086]
ns-ns-domain-year ::=
  ns-decimal-digit x 4 
/* type family domain ownership year */
[087]
ns-ns-domain-day-month ::=
  ns-decimal-digit x 2 
/* type family domain ownership day or month (01 by default) */

3.3.6 Anchor

An anchor is a property that can be used to mark a node for future reference. An alias node can then be used to indicate additional inclusions of an anchored node by specifying the node's anchor.

[088]
c-ns-anchor-property ::=
  c-anchor ns-ns-anchor-name 
/* associates an anchor with a given node */
[089]
ns-ns-anchor-name ::= ns-char
/* unique anchor name */

3.4 Alias

An alias node does not directly exist in the data serialized in the stream. Instead, it represents a second occurence of the data represented by the anchored node. The first occurence of the node must be marked by an anchor to allow additional occurences to be represented as alias nodes.

An alias refers to the most recent preceding node having the same anchor. It is an error to have an alias use an anchor that does not occur previously in the serialization of the document. It is not an error to have an anchor that is not used by any alias node.

[090]
ns-ns-alias ::= c-alias ns-ns-anchor-name 
/* alias of a preceding anchored node */
anchor : &A001 This scalar has an anchor.
override : &A001 The alias node below is a repeated use of this value.
alias : *A001 

3.5 Collection

Collection nodes come in two kinds, sequence and mapping. Each kind has two styles, block and flow. Block styles begin on the next line and use indentation for internal structure. Flow collection styles start on the current line, may span multiple lines, and rely on indicators to represent internal structure.

[091]
l-l-blk-collection(n) ::=
    l-l-blk-sequence(n)
  | l-l-blk-mapping(n) 
/* block collection node styles */
[092]
c-c-flow-collection(n) ::=
    c-c-flow-sequence(n)
  | c-c-flow-mapping(n) 
/* flow collection node styles */

To enable line spanning in flow collections, wherever tokens may be separated by white space, it is possible to end the line (with an optional throwaway comment) and continue the collection in the next line. Line spanning functionality is indicated by the use of the s-s-optional(n) space and the s-s-required(n) space productions.

[093]
s-s-optional(n) ::=
    s-char*
  | ( s-b-trailing-comment
      i-spaces(n) s-char+ ) 
/* optional white space separating tokens */
[094]
s-s-required(n) ::=
    s-char+
  | ( s-b-trailing-comment
      i-spaces(n) s-char+ ) 
/* required white space separating tokens */

3.5.1 Sequence

A sequence node is the simplest node kind. It is a an ordered collection of sub-nodes at a higher indentation level. A flow style is available for short, simple sequences. Also, if a sub-sequence node has no properties, and its first entry is specified without any properties, the sub-sequence node may immediately follow the sequence entry indicator.

[095]
l-l-blk-sequence(n) ::=
  ( i-spaces(n[-1])
    c-l-blk-seq-entry(n[-1]) )+ 
/* block sequence node; -1 unless the block sequence is the value of an entry of a parent block sequence */
[096]
c-l-blk-seq-entry(n) ::=
  c-sequence-entry
  ( s-l-top-value-node(>n)
  | i-l-seq-in-seq(n)
  | i-l-map-in-seq(n)
/* block sequence node entry */
[097]
i-l-seq-in-seq(n) ::=
  i-spaces(m)
  c-l-blk-seq-entry(n+m+1)
  l-l-blk-sequence(n+m+1)
/* sequence node with no properties in a sequence entry (where m > 0) */
[098]
c-c-flow-sequence(n) ::=
  c-sequence-start
  s-s-optional(n)
  ( ns-ns-flow-value-node(n)
    s-s-optional(n)
    ( c-collect-entry
      s-s-required(n)
      ns-ns-flow-value-node(n)
      s-s-optional(n) )* )?
  c-sequence-end 
/* flow sequence node */
empty: []
flow: [ one, two, three # May span lines,
         , four,        # indentation is
           five ]       # mostly ignored.
block:
- Note indicator is not indented.
-
 - Subordinate sequence entry (note must be indented).
 - Another entry in subordinate sequence
- - Another way to write a sub-sequence
  - Another entry in sub-sequence
- >
 A folded sequence entry (fifth entry) 

3.5.2 Mapping

A mapping node is an unordered association of unique keys with values. It is an error for two equal key entries to appear in the same mapping node. In such a case the processor may continue, ignoring the second key and issuing an appropriate warning. This strategy preserves a consistent information model for streaming and random access applications.

A flow form is available for short, simple mapping nodes. Also, if a mapping node has no properties, and its first key is specified as a flow scalar without any properties, this first key may immediately follow the sequence entry indicator.

[099]
l-l-blk-mapping(n) ::=
  ( i-spaces(n)
    ns-l-blk-map-entry(n) )+ 
/* block mapping node */
[100]
i-l-map-in-seq(n) ::=
  i-spaces(m)
  ns-ns-flow-scalar-key(n+m+1)
  s-char*
  c-mapping-entry
  s-l-top-value-node(>n+m+1)
  l-l-blk-mapping(n+m+1)
/* mapping node with no properties in a sequence entry (where m > 0) */
[101]
ns-l-blk-map-entry(n) ::=
  ns-s-top-key-node(n)
  c-mapping-entry
  s-l-top-value-node(>n) 
/* single key:value pair */
[102]
c-c-flow-mapping(n) ::=
  c-mapping-start
  s-s-optional(n)
  ( ns-ns-flow-map-entry(n)
    s-s-optional(n)
    ( c-collect-entry
      s-s-required(n)
      ns-ns-flow-map-entry(n)
      s-s-optional(n) )* )?
  c-mapping-end 
/* flow mapping node */
[103]
ns-ns-flow-map-entry(n) ::=
  ns-ns-flow-key-node(n)
  s-char*
  c-mapping-entry
  s-s-required(n)
  ns-ns-flow-value-node(n) 
/* flow key:value pair */
empty: {}
flow: { one: 1, two: 2 }
spanning: { one: 1,
   two: 2 }
block:
 key : value
 nested mapping:
  key: Subordinate mapping
 nested sequence:
  - Subordinate sequence
!float 12 : This key is a float.
"\a" : This key had to be escaped.
? '?'
: This key had to be quoted.
? >
 This is a multi
 line folded key
: Whose value is
  also multi-line.
? this also works as a key
: with a value at the next line.
?
 - This key
 - is a sequence
:
 - With a sequence value.
?
 This: key
 is a: mapping
:
 with a: mapping value.
---
- A key: value pair in a sequence.
  A second: key:value pair.
- The previous entry is equal to the following one.
-
 A key:
     value pair in a sequence.
 A second:
     key:value pair. 

3.6 Scalar

While most of the document productions are fairly strict, the scalar production is generous. It offers three flow style variants and two block style variants to choose from, depending upon the readability requirements.

Throwaway comments may follow a scalar node, but may not appear inside one. The comment lines following a block scalar node must be less indented than the block scalar value. Empty lines in a scalar node that are followed by a non-empty content line are interpreted as content rather than as implicit comments. Such lines may be less indented than the text content.

[104]
c-l-blk-scalar(n) ::=
    c-l-literal(n)
  | c-l-folded(n) 
/* block scalar styles */
[105]
ns-ns-top-scalar-value(n) ::=
    c-c-single-quoted(n)
  | c-c-double-quoted(n)
  | ns-ns-plain-top-value(n) 
/* flow scalar value styles outside flow collection */
[106]
ns-ns-flow-scalar-value(n) ::=
    c-c-single-quoted(n)
  | c-c-double-quoted(n)
  | ns-ns-plain-flow-value(n) 
/* flow scalar value styles inside flow collection */
[107]
ns-ns-flow-scalar-key(n) ::=
    c-c-single-quoted(n)
  | c-c-double-quoted(n)
  | ns-ns-plain-key 
/* flow scalar key styles */

3.6.1 End Of line Normalization

Inside all scalar nodes, a compliant YAML parser must translate the two-character combination CR LF, any CR that is not followed by an LF, and any NEL into a single LF (this does not apply to escaped characters). LS and PS characters are preserved. These rules are compatible with Unicode's newline guidelines.

Normalization functionality is indicated by the use of the b-as-line-feed production defined below.

[108]
b-as-line-feed ::= b-generic 
/* line break converted to a line feed */
[109]
b-normalized ::=
  b-as-line-feed | b-specific 
/* a normalized end of line marker */

On output, a YAML emitter is free to serialize end of line markers using whatever convention is most appropriate, though again LS and PS must be preserved.

3.6.2 Block Modifiers

Each block scalar may have explicit indentation and chomping modifiers. These modifiers are specified following the block style indicator. It is an error for the same modifier to be specified more than once for the same node.

[110]
ns-ns-blk-modifiers ::=
    ( ns-explicit-indent
      c-chomp-control? )
  | ( c-chomp-control
      ns-explicit-indent? ) 
/* block scalar modifiers */

3.6.3 Explicit Indentation

Typically the indentation level of a block scalar node is detected from its first content line. This detection fails when this first line is empty, contains a leading '#' character, or contains leading white space characters.

In such cases YAML requires that the indentation level for the scalar node text content be given explicitly. This level is specified as the integer number of the additional indentation spaces used for the text content.

The indentation level is always non-zero, except for the top level node of each document. This node is commonly indented by zero spaces (not indented).

It is always valid to specify an explicit indentation level, though emitters should not do so in cases where detection succeeds. It is an error for detection to fail when there is no explicit indentation specified.

[111]
ns-explicit-indent ::= ns-decimal-digit 
/* explicit additional indentation level */
# Explicit indentation must
# be given in all the three
# following cases.
leading spaces: |2
      This value starts with four spaces.

leading line break: |2

  This value starts with a line break.

leading comment indicator: |2
  # first line starts with a # character.

# Explicit indentation may
# also be given when it is
# not required.
redundant: |2
  This value is indented 2 spaces.

# Indentation may apply to top level nodes.
--- |
Usually top level nodes are not indented.
--- |
  This text is indented two spaces.
  It contains no leading spaces.
--- |0
  This text contains two leading spaces. 

3.6.4 Chomping

Typically the final line break of a block scalar is considered to be a part of its value, and any trailing empty lines are taken to be comment lines. This default "clip" chomping behavior can be overriden by specifying a chomp control modifier.

[112]
c-chomp-control ::=
    c-strip-chomp
  | c-keep-chomp 
/* override the default "clip" chomping */
[113]
c-strip-chomp ::= '-' 
/* strip final line break from value */
[114]
c-keep-chomp ::= '+' 
/* keep trailing line breaks in value */
strip ('-')
The '-' chomp control specifies that the final line break character of the block scalar should be stripped from its value.
keep ('+')
The '+' chomp control specifies that any trailing empty lines following the block scalar should be considered to be a part of its value. If this modifier is not specified, such lines are considered to be empty throwaway comment lines and are ignored.

When this functionality is implied, the l-l-empty-trailing(n) production will be used.

[115]
l-l-empty-trailing(n) ::=
    l-empty-comment(n)+
  | l-blk-empty-line-feed(n)
/* trailing line feeds or comment lines, depending on chomp control) */
[116]
l-blk-empty-line-feed(n) ::=
  i-spaces(<=n) b-as-line-feed 
/* empty block line */
clipped: |
    This has one newline.

same as "clipped" above: "This has one newline.\n"

stripped: |-
    This has no newline.

same as "stripped" above: "This has no newline."

kept: |+
    This has two newlines.

same as "kept" above: "This has two newlines.\n\n" 

3.6.5 Literal

A literal scalar is the simplest scalar form. No processing is performed on literal scalar characters aside from end of line normalization and stripping away the indentation. Indentation is detected from the first content line. Explicit indentation must be specified in case this yields the wrong result.

This restricts literal scalars to printable characters only. Also, long lines can't be broken. In exchange for these restrictions, a literal scalar may use any printable character, including line breaks. This makes literal scalars the most readable format for source code or other text values with significant use of indicators, quotes, escape sequences, and line breaks.

[117]
c-l-literal(n) ::=
  c-literal
  ns-ns-blk-modifiers?
  s-b-trailing-comment
  l-l-literal-value(n)?
  l-l-empty-trailing(n)?
  ( l-text-comment(n)
    l-comment(any)* )? 
/* literal scalar */
[118]
l-l-literal-value(n) ::=
  l-l-literal-chunk(n)
/* value of literal scalar */
[119]
l-l-literal-chunk(n) ::=
  l-blk-empty-line-feed(n)*
  ( l-literal-text(n)
  | l-blk-empty-specific(n)
/* chunk of literal scalar lines */
[120]
l-blk-empty-specific(n) ::=
  i-spaces(<=n) b-specific 
/* empty block line with preserved specific line break */
[121]
l-literal-text(n) ::=
  i-spaces(n) nb-char+ b-normalized 
/* literal line character data */
empty: |

literal: |
 The \ ' " characters may be
 freely used. Leading white
    space is significant.

 Line breaks are significant. Thus this value
 contains one empty line and ends with a single
 line break, but does not start with one.

is equal to: "The \\ ' \" characters may \
 be\nfreely used. Leading white\n   space \
 is significant.\n\nLine breaks are \
 significant. Thus this value\ncontains \
 one empty line and ends with a single\nline \
 break, but does not start with one.\n"

# Comments may follow a block scalar value.
# They must be less indented.

# Modifiers may be combined in any order.
indented and chomped: |2-
    This has no newline.

also written as: |-2
    This has no newline.

both are equal to: "  This has no newline." 

3.6.6 Folding

When folding is done, a single normalized line feed is converted to a single space (#x20). When two or more consecutive (possibly indented) normalized line feeds are encountered, the parser does not convert them into spaces. Instead, the parser ignores the first of the line feeds and preserves the rest. Thus a single line feed can be serialized as two, two line feeds can be serialized as three, etc.

When folding is done, specific line breaks are preserved and may be safely used to convey text structure.

Folding block scalars

Block scalars are based on indentation to convey structure. Hence leading white space in block scalar lines is always significant. Folding block scalars builds on this fact to offer powerful and intuitive semantics.

In block scalars, folding only applies to line feeds that separate text lines starting with a non-space character. Hence, folding does not apply to leading line feeds, line feeds surrounding an empty line ending with a specific line break, or line feeds surrounding a text line that starts with a space character.

The combined effect of the processing rules above is that each "paragraph" is interpreted as a single line, empty lines are used to represent a line feed, and "more indented" lines are preserved. Also, specific line breaks may be safely used to indicate text structure.

[122]
b-as-space ::= b-generic 
/* line feed converted to a space */
[123]
b-ignored ::= b-generic 
/* ignored line feed */
[124]
b-l-blk-trimmed(n) ::=
  b-ignored
  l-blk-empty-line-feed(n)
/* sequence of line feeds in block scalar */
Folding flow scalars

Flow scalars depend on explicit indicators to convey structure, rather than indentation. Hence, in such scalars, all line space preceding or following a line break is not considered to be part of the scalar value. Hence folding flow scalars provides a more relaxed, less powerful semantics. In flow scalars, all leading and trailing white space is stripped from each line. All generic line breaks are folded (even if the line was "more indented").

The combined effect of these processing rules is that each "paragraph" is interpreted as a single line, empty lines are used to represent a line feed, and text can be freely "indented" without affecting the scalar value. Again, specific line breaks may be safely used to indicate text structure.

[125]
i-s-ignored-leading(n) ::=
  i-spaces(n) s-char
/* ignored spaces at start of flow scalar line */
[126]
s-s-ignored-trailing ::= s-char
/* ignored spaces at end of flow scalar line */
[127]
l-flow-empty-specific(n) ::=
  ( i-spaces(<=n)
  | i-s-ignored-leading(n) )
  b-specific 
/* empty flow line with preserved specific line break */
[128]
l-flow-empty-line-feed(n) ::=
  ( i-spaces(<=n)
  | i-s-ignored-leading(n) )
  b-as-line-feed 
/* empty flow line with line break normalized to line feed */
[129]
b-l-flow-trimmed(n) ::=
  b-ignored
  l-flow-empty-line-feed(n)
/* sequence of line feeds in flow scalar */
[130]
s-l-end-flow-line(n) ::=
  s-s-ignored-trailing
  ( b-as-space
  | b-l-flow-trimmed(n)
  | b-specific
/* end of a line in a multi-line flow scalar */

3.6.7 Folded

A folded scalar is similar to a literal scalar. However, unlike a literal scalar, a folded scalar is subject to (block) line folding. This allows long lines to be broken anywhere a space character (#x20) appears, at the cost of requiring an empty line to represent each line feed character.

[131]
c-l-folded(n) ::=
  c-folded
  ns-ns-blk-modifiers
  s-b-trailing-comment
  l-l-folded-value(n)?
  l-l-empty-trailing(n)?
  ( l-text-comment(n)
    l-comment(any)* )? 
/* folded scalar */
[132]
l-l-folded-value(n) ::=
  l-blk-empty-line-feed(n)*
  ( l-l-folded-chunk(n)
  | l-l-non-folded-chunk(n)
/* value of folded scalar */
[133]
l-l-folded-chunk(n) ::=
  ( i-nb-folded-paragraph(n)
    b-l-blk-trimmed(n) )*
  i-nb-folded-paragraph(n)
  b-l-after-folded-chunk(n) 
/* value starting with a chunk of folded text */
[134]
i-nb-folded-paragraph(n) ::=
  ( i-nb-folded-text(n)
    b-as-space )*
  i-nb-folded-text(n) 
/* single content paragraph folded into multiple physical lines */
[135]
i-nb-folded-text(n) ::=
  i-spaces(n) ns-char nb-char
/* folded text line characters */
[136]
b-l-after-folded-chunk(n) ::=
  b-normalized
  ( l-blk-empty-line-feed(n)*
    l-l-non-folded-chunk(n) )? 
/* text following a folded text chunk */
[137]
l-l-non-folded-chunk(n) ::=
  ( l-empty-non-folded(n)
  | l-indented-non-folded(n) )
  l-l-folded-value(n)
/* value starting with non-folded text chunk */
[138]
l-empty-non-folded(n) ::=
  i-spaces(<=n) b-specific 
/* not folded due to specific line break */
[139]
l-indented-non-folded(n) ::=
  i-spaces(n) s-char nb-char*
  b-normalized 
/* not folded due to starting white space */
empty: >

one paragraph: >
 Line feeds are converted to spaces,
 so this value contains no line
 breaks except for the final one.

multiple paragraphs: >2

  An empty line, either at
  the start or in the value:

  Is interpreted as a line
  break. Thus this value
  contains three line breaks.

indented text: >
    This is a folded paragraph
    followed by a list:
     * first entry
     * second entry
    Followed by another folded
    paragraph, another list:

     * first entry

     * second entry

    And a final folded
    paragraph.

above is equal to: |
    This is a folded paragraph followed by a list:
     * first entry
     * second entry
    Followed by another folded paragraph, another list:

     * first entry

     * second entry

    And a final folded paragraph.

# Explicit comments may follow
# but must be less indented. 

3.6.8 Single Quoted

The single quoted flow scalar style is indicated by surrounding ''' characters. Therefore, within a single quoted scalar such characters need to be escaped. No other form of escaping is done, limiting single quoted scalars to printable characters.

Single quoted scalars are subject to (flow) folding. This allows empty lines to be broken everywhere a single space character (#x20) separates non-space characters, at the cost of requiring an empty line to represent each line feed character.

[140]
c-c-single-quoted(n) ::=
  c-single-quote
  nb-nb-single-quoted-value(n)?
  c-single-quote 
/* single quoted scalar */
[141]
nb-nb-single-quoted-value(n) ::=
    nb-nb-one-single-line
  | ( nb-l-first-single-line(n)
      l-l-inner-single-line(n)*
      i-nb-last-single-line(n)
/* value of a single quoted scalar */
[142]
nb-nb-one-single-line ::=
  nb-single-char
/* one line value of single quoted scalar */
[143]
nb-l-first-single-line(n) ::=
  ( nb-single-char* ns-single-char )?
  s-l-end-flow-line(n) 
/* first line of multi-line single quoted scalar */
[144]
l-l-inner-single-line(n) ::=
    l-flow-empty-specific(n)
  | ( i-s-ignored-leading(n)
      ns-single-char
      nb-l-first-single-line(n)
/* inner line of multi-line single quoted scalar */
[145]
i-nb-last-single-line(n) ::=
  i-s-ignored-leading(n)
  ( ns-single-char nb-single-char* )? 
/* last line of multi-line single quoted scalar */
[146]
ns-escaped-single-quote ::=
  c-single-quote c-single-quote 
/* indicates a single quote */
[147]
nb-single-char ::=
    ns-escaped-single-quote
  | ( nb-char - c-single-quote
/* non-break char valid in a single quoted scalar */
[148]
ns-single-char ::=
  nb-single-char - s-char 
/* non-space char valid in a single quoted scalar */
empty: ''
second:
  '! : \ etc. can be used freely.'
third: 'a single quote '' must be escaped.'
span: 'this contains
      six spaces

      and one
      line break'
is same as: "this contains six spaces\nand one line break" 

3.6.9 Escaping

Escaping allows YAML scalar nodes to specify arbitrary Unicode characters, using C-style escape codes. Non-escaped nodes are restricted to printable Unicode characters.

[149]
c-escape ::= '\' 
/* indicates an escape sequence */
[150]
ns-esc-escape ::= c-escape c-escape 
/* escaped backslash */
[151]
ns-esc-double-quote ::=
  c-escape c-double-quote 
/* escaped double quote character */
[152]
ns-esc-bel ::= c-escape 'a' 
/* ASCII alert (BEL) */
[153]
ns-esc-backspace ::= c-escape 'b' 
/* ASCII backspace (BS) */
[154]
ns-esc-esc ::= c-escape 'e' 
/* ASCII escape (ESC) */
[155]
ns-esc-form-feed ::= c-escape 'f' 
/* ASCII formfeed (FF) */
[156]
ns-esc-line-feed ::= c-escape 'n' 
/* ASCII linefeed (LF) */
[157]
ns-esc-return ::= c-escape 'r' 
/* ASCII carriage return (CR) */
[158]
ns-esc-tab ::= c-escape 't' 
/* ASCII horizontal tab (TAB) */
[159]
ns-esc-vertical-tab ::= c-escape 'v' 
/* ASCII vertical tab (VTAB) */
[160]
ns-esc-null ::= c-escape '0' 
/* ASCII zero (NUL) */
[161]
ns-esc-space ::= c-escape #20 
/* ASCII space (SP) */
[162]
ns-esc-non-breaking-space ::=
  c-escape '_' 
/* Unicode non-breaking space (NBSP) */
[163]
ns-esc-next-line ::= c-escape 'N' 
/* Unicode next line (NEL) */
[164]
ns-esc-line-separator ::= c-escape 'L' 
/* Unicode line separator (LS) */
[165]
ns-esc-paragraph-separator ::= c-escape 'P' 
/* Unicode paragraph separator (PS) */
[166]
ns-esc-8-bit ::=
  c-escape 'x' ( ns-hex-digit x 2 ) 
/* 8-bit character */
[167]
ns-esc-16-bit ::=
  c-escape 'u' ( ns-hex-digit x 4 ) 
/* 16-bit character */
[168]
ns-esc-32-bit ::=
  c-escape 'U' ( ns-hex-digit x 8 ) 
/* 32-bit character */
[169]
ns-esc-sequence ::=
    ns-esc-escape
  | ns-esc-double-quote
  | ns-esc-bel
  | ns-esc-backspace
  | ns-esc-esc
  | ns-esc-form-feed
  | ns-esc-line-feed
  | ns-esc-return
  | ns-esc-tab
  | ns-esc-vertical-tab
  | ns-esc-null
  | ns-esc-space
  | ns-esc-non-breaking-space
  | ns-esc-next-line
  | ns-esc-line-separator
  | ns-esc-paragraph-separator
  | ns-esc-8-bit
  | ns-esc-16-bit
  | ns-esc-32-bit 
/* escape codes in escaped scalars */

An escaped line break is completely ignored.

[170]
b-escaped ::= c-escape b-any 
/* escaped (ignored) line break */

3.6.10 Double Quoted

The double quoted style variant adds escaping to the single quoted style variant. This is indicated by surrounding '"' characters. Escaping allows arbitrary Unicode characters to be specified at the cost of some verbosity: escaping the printable '\' and '"' characters. It is an error for a double quoted value to contain invalid escape sequences.

Like single quoted scalars, double quoted scalars may span multiple lines, resulting in a single space content character for each line break. If the line break is escaped, any white space preceding it is preserved, and the line break and any leading white space in the continuation line are discarded.

[171]
c-c-double-quoted(n) ::=
  c-double-quote
  nb-nb-double-quoted-value(n)?
  c-double-quote 
/* double quoted scalar */
[172]
nb-nb-double-quoted-value(n) ::=
    nb-nb-one-double-line
  | ( nb-l-first-double-line(n)
      l-l-inner-double-line(n)*
      i-nb-last-double-line(n)
/* value of a double quoted scalar */
[173]
nb-nb-one-double-line ::=
  nb-double-char
/* one line value of double quoted scalar */
[174]
nb-l-first-double-line(n) ::=
  ( nb-double-char* ns-double-char )?
  s-l-end-double-line(n) 
/* first line of multi-line double quoted scalar */
[175]
l-l-inner-double-line(n) ::=
    l-flow-empty-specific(n)
  | ( i-s-ignored-leading(n)
      ns-double-char
      nb-l-first-double-line(n)
/* inner line of multi-line double quoted scalar */
[176]
i-nb-last-double-line(n) ::=
  i-s-ignored-leading(n)
  ( ns-double-char nb-double-char* )? 
/* last line of multi-line double quoted scalar */
[177]
s-l-end-double-line(n) ::=
    s-l-end-flow-line(n)
  | ( s-char* b-escaped
/* end of a line in a multi-line double quoted scalar */
[178]
nb-double-char ::=
    ns-esc-sequence
  | ( nb-char - c-escape
/* non-break char valid in a double quoted scalar */
[179]
ns-double-char ::=
  nb-double-char - s-char 
/* non-space char valid in a double quoted scalar */
empty: ""
second: "! : etc. can be used freely."
third: "a \" or a \\ must be escaped."
fourth:
  "this value ends with an LF.\n"
span: "this contains
  four  \
      spaces"
is equal to: "this contains four  spaces" 

3.6.11 Plain

The plain style variant is a restricted form of the single quoted style variant. As it has no identifying markers, it may not start or end with white space characters, may not start with most indicators, and may not contain certain indicators. Also, a plain scalar is subject to implicit typing. This can be avoided by providing an explicit transfer method property.

Since it lacks identifying markers, the restrictions on a plain scalar depends on the context. There are three different such contexts, with increasing restrictions. Top level plain values are the least restricted plain scalar format. While they can't start with most indicators, they may contain any indicator except ' #' and ': '. Plain scalars used in flow collections are further restricted not to contain flow indicators. Finally, plain keys are further restricted to a single line.

[180]
ns-ns-plain-top-value(n) ::=
  ns-ns-plain-value(n) 
/* avoiding top indicator chars */
[181]
ns-ns-plain-flow-value(n) ::=
  ns-ns-plain-value(n) 
/* avoiding flow indicator chars */
[182]
ns-ns-plain-key ::=
  ns-ns-one-plain-line 
/* plain scalar used as a key; avoiding flow indicator chars */
[183]
ns-ns-plain-value(n) ::=
    ns-ns-one-plain-line
  | ( ns-l-first-plain-line(n)
      l-l-inner-plain-line(n)*
      i-ns-last-plain-line(n)
/* plain scalar used as a value */
[184]
ns-ns-one-plain-line ::=
  ns-first-plain-char
  nb-ns-plain-text
/* plain one-line value */
[185]
ns-l-first-plain-line(n) ::=
  ns-ns-one-plain-line
  s-l-end-flow-line(n) 
/* first line of multi-line plain scalar */
[186]
l-l-inner-plain-line(n) ::=
    l-flow-empty-specific(n)
  | ( i-s-ignored-leading(n)
      ns-plain-char
      nb-ns-plain-text?
      s-l-end-flow-line(n)
/* inner line of multi-line plain scalar */
[187]
i-ns-last-plain-line(n) ::=
  i-s-ignored-leading(n)
  ( ns-plain-char
    nb-ns-plain-text? )? 
/* last line of multi-line plain scalar */
[188]
nb-ns-plain-text ::=
  nb-plain-char* ns-plain-char 
/* chunk of plain text */
[189]
ns-first-plain-char ::=
    ( ns-plain-char
    - c-sequence-entry
    - c-mapping-entry
    - c-sequence-start
    - c-sequence-end
    - c-mapping-start
    - c-mapping-end
    - c-collect-entry
    - c-top-key
    - c-alias
    - c-anchor
    - c-transfer
    - c-literal
    - c-folded
    - c-single-quote
    - c-double-quote
    - c-throwaway
    - c-directive
    - c-reserved
  | ( ( c-sequence-entry
      | c-top-key
      | c-mapping-entry
      | c-collect-entry )
      ns-plain-char
/* first character in a plain scalar */
[190]
nb-plain-top-char ::=
    ( nb-char
    - c-mapping-entry
    - c-throwaway )
  | ( ns-plain-char
      c-throwaway )
  | ( c-mapping-entry
      ns-plain-char
/* char allowed in plain scalar used as top level value */
[191]
nb-plain-flow-char ::=
    ( nb-plain-top-char
    - c-sequence-start
    - c-sequence-end
    - c-mapping-start
    - c-mapping-end
    - c-collect-entry )
  | ( c-collect-entry
      ns-plain-char
/* char allowed in plain scalar used as value in a flow collection */
[192]
nb-plain-key-char ::=
  nb-plain-flow-char 
/* char allowed in plain scalar used as key */
[193]
nb-plain-char ::=
    nb-plain-top-char
  | nb-plain-flow-char
  | nb-plain-key-char 
/* depending whether reached from top, flow or key plain scalar production */
[194]
ns-plain-char ::=
  nb-plain-char - s-char 
/* non-space char valid in a plain scalar */
first: There is no unquoted empty string.
second: 12          ## This is an integer.
boolean: -          ## This is (false).
third: !str 12      ## This is a string.
span: this contains
      six spaces

      and one
      line break

indicators: this has no comments.
            #:foo and bar# are
            both text.
flow: [ can span
           lines, # comment
             like
           this ]
note: { one-line keys: but
        multi-line values } 

4 Information Models

4.1 Overview

Constraints beyond the syntax productions are required for the consistency of generic YAML utilities such as schema language, transformation tool, path selection expressions, and bindings between languages. These constraints are best expressed as a set of models describing the various states of processing YAML. A conforming YAML processor must satisfy these constraints.

YAML processing may be understood in terms of four interacting representations of the data: a textual format, an event stream, a generic node graph and native language data structures. For each one of these representations, there is a corresponding information model.

Translating YAML information between these representations are six processing components: a parser, a linker, a loader, a dumper, a serializer and an emitter. The parser extracts structured information from the text stream. The linker resolves aliases in the resulting tree, creating a directed graph. The loader resolves types and formats and converts this graph to native data structures. The dumper, serializer and emitter perform the inverse operations.

  TEXT   -- Parser -> SERIAL --- Linker --->  GRAPH    -- Loader ->   NATIVE
(syntax) <- Emitter - (tree) <- Serializer - (generic) <- Dumper -- (language)
                                                                        /\
                                                                        ||
                                                                        \/
                                                                   Application 

A processor need not expose the event stream (serial model) or generic view (graph model) and may translate directly between a text stream and the native binding. However, such a direct translation should take place so that the native binding is constructed only from information available in the native model. In particular, information specific to the graph model (format), serial model (alias anchors and pair ordering) and text model (comments and styles) must not be relied upon in the construction of the native representation. Exceptions to this guideline include editors that must operate directly on the syntax.

native model
The native model describes any information which can be represented as YAML. Information native to a specific environment is modeled by YAML as a graph of typed nodes, where nodes in the graph include atomic values called scalars, sequences of nodes, or mappings of nodes from one set to another.

The native model may be implemented by arbitrary native data structures of the programming language used. The only constraint on the native representation is that it preserve the information defined by the native model.

graph model
The graph model uses formats to provide a view of native data structures in a way which is independent of particular platform, language, or application. This allows for the definition of a generic YAML API and corresponding tools that do not depend on any particular native representation.

Implementations of the graph model are, by necessity, specific to a particular programming language. Such implementations are constrained to provide the information specified by the graph model.

serial model
The serial model flattens the graph structure into an ordered hierarchy using alias nodes. An alias node is a surrogate used for subsequent occurrences of any kind of node. In this model, mappings are represented as an ordered set of node pairs.

The serial model is often implemented as an event stream, and is important for implementing one-pass operations on YAML data. Again, of necessity implementations are specific to a particular programming language, and are constrained to provide the information required by the serial model.

text model
The text model enhances the serial model with comments, styles and other syntax specific details. YAML text must comply with the syntax productions given in the following section.

YAML text syntax is fully defined by this specification and hence any instance is independent of the particular programming language chosen. This allows the definition of generic YAML tools that may be applied independently of the programming language used, as well as provides a way to interchange data between applications implemented in differing languages.

The "human" view of YAML data contains presentation elements (comments, styles, anchors, key order, format) that are absent from the "machine" view of the data. In a similar manner, for human readable text, it is frequently desirable to omit data typing information which is often obvious to the human reader and not needed. This is especially true if the information is created by hand, expecting humans to bother with data typing detail is optimistic.

4.2 Native (Language) Model

The native model abstracts data structures of common programming languages. In YAML's view, any native data is viewed as a directed graph of typed nodes. Nodes that are defined in terms of other nodes are collections and nodes that are defined independent of any other nodes are scalars. YAML supports two kinds of collection nodes, mappings and sequences. The native model also defines when two different nodes have the same content and provides a definition of node identity.

4.2.1 Native Node

A native node is YAML's building block for data structures. A native node stands for anything from a single integer to a complex data structure such as a complete VRML scene or SQL database. A native node has the following properties:

type family
Each native node is associated with a type family. This association may be based on the native data type of the node or its value. Indirectly each node is also associated with a kind through its family.
value
A node has an associated value. This value must satisfy the constraints specified by the type family. In particular, the value of a collection (mappings and sequences) is given in terms of other nodes, while the value of a scalar is defined independent of any other node.

4.2.2 Type Family

The type family mechanism provides an abstraction of data types that is portable across languages and platforms. Each native binding may have zero or more native concrete types or class constructs that correspond to a given type family.

YAML supports both global and private type families. Global type families have consistent semantics across all YAML documents. Private type families should not be expected to maintain the same semantics in different documents, even if these appear in the same document stream.

name
Global type family names are URIs under the taguri: scheme. Private type family names are URIs under the x-private: scheme. The taguri: scheme is described in http://www.taguri.org.

YAML only makes use of taguri: URIs that take the form taguri:domain,date:identifier. Specifically, it does not make use of taguri: URIs that are based on an E-mail address. Nor does it make use of URIs outside the taguri: scheme.

definition
A description of the particular category of information, independent of language and platform.
kind

Each type family must have a kind that is either a scalar or a collection. There are two kinds of collections, sequence and mapping. Usually the kind of each type family follows immediately from the definition (for example, integers are scalars while Point structures are mappings). In other cases, deciding on the kind requires a data modeling decision (for example, whether a date is thought of as a single scalar or as a mapping with independent sub-parts).

scalar
Scalar type families are the simplest. The value of a scalar node is defined in some mathematical terms, independent of any other nodes and type families.
sequence
The value of a sequence node is defined as an ordered set of nodes. Each sequence type family may impose additional constraints on these nodes. For example, it may require that they belong to particular type families.
mapping

The value of a mapping node is defined as a function from a domain to a range. Each mapping type family may impose additional constraints. For example, it may require a specific set of keys and that the value for each key must be of a particular type family.

domain
A domain is an unordered set of nodes, restricted such that no two nodes in the set may be equal. Nodes that are members of the domain are often called "keys".
range
A range is an unordered set of nodes without restrictions. Nodes that are members of the range are often called "values".
function
A function is a rule of correspondence from the domain onto the range such that there is a unique value in the range assigned to every key in the domain, and every value in the range is assigned to at least one key.
collection
Is possible to think of a sequence as a mapping using a special domain (all integer values between zero and some maximal value). A unified collection model is helpful both for theoretical analysis and in constructing practical YAML tools and APIs.

4.2.3 Equivalence

In most programming languages, there are two distinct manners in which variables can be equivalent.

identity
The first form of equivalence is by reference, where the two variables refer to the same memory address. We call this equivalence relation "identity".
equality

The second form of equivalence occurs when two nodes are different (have different memory addresses), but have the same content. We call this second form of equivalence "equality". It follows that when two nodes are identical they are also equal.

Equality is defined between scalar nodes and between collection nodes, as described below.

scalar equality
Two scalar nodes are equal if and only if they have the same type family and their values are the same under the type family's definition
collection equality
Equality of collections is defined recursively. Two collection nodes are equal if and only if they have the same type family and for each key in the domain of one, there is a corresponding key in the domain of the other such that both keys are equal and their corresponding values are equal; here corresponding value refers to the unique node in the range of the collection assigned to the key by the collection's function.

For the purpose of node equivalence, all YAML collection type families are considered to be mutable and all scalar type families are considered to be immutable. It is possible to modify the value of a mutable (collection) node "in place". For immutable (scalar) nodes, it is impossible to do so; instead, modifications require the creation of a new, independent scalar value of the same type family and using it instead. To better understand this distinction, consider the following example:

C syntax: |
    struct Point { int x; int y; } p = { 1, 2 };
YAML syntax: !Point { x: 1, y: 2 } 

It is impossible to modify the integer value 1. The only modification possible is constructing a new, unrelated integer value 3 and using this new value for the X coordinate. Performing this replacement would cause the point to change "in place" from { x: 1, y: 2 } to { x: 3, y: 2 }. Thus, in this example points are mutable but integers are not.

For immutable (scalar) type families, the distinction between equal and identical nodes is only of interest for efficiency reasons (reducing memory usage), and has no semantic significance. Hence for such type families a YAML processor may freely replace two equal but separate (non-identical) nodes with two occurrences of the same (identical) node, and vice versa.

For mutable (collection) type families, however, the distinction between equality and indentity is an important part of the information model and a YAML processor is required to preserve node identity.

4.2.4 Documents Stream

A YAML stream is a sequence of disjoint directed graphs, each with a root node.

stream
A sequence of zero or more document root nodes.
document
A top-level node that is disjoint from all other root document nodes.

The term disjoint means that for any two nodes x and y, there does not exist a third node z that is reachable from both x and y. For any node x, x is reachable from y if and only if either x and y are identical, or y is a collection and there exists a node z in the domain or the range of y such that x is reachable from z.

4.3 Graph (Generic) Model

To access YAML information through a generic API, scalars must be viewed as strings. Since a native data type may be stringified in more than one way, the graph model extends the native model with the concept of a format. This model allows the operation of generic tools to be defined independent of language. Applications constructing a native binding from the graph model should not use formats for the preservation of important data.

4.3.1 Format

It may be possible to write a string value of a scalar in more than one way. For example, an integer value of 255 can also be written in hex as 0xFF. This distinction is covered by the concept of a format. A format defines a way to write the values of a scalar type family as Unicode strings. Using formats allows generic YAML APIs to be implemented in terms of such strings and still allow handling of arbitrary native data.

name
Each format has a name used for explicit typing. This name may also be used as a fragment identifier in combination with the type family URI for general identification. This name must comply with the format production, and must be unique within the type families it applies to.
definition
A description of the format as it applies to particular data values.
regexp
Regular expressions may be provided to allow implicit typing using the string format, or to enable the YAML processor to validate that a given value is indeed compliant with the string format.

Formats are an extension required by the graph model, and are not part of the native model. Hence, when constructing native data structures from YAML data, format need not be preserved. For example, a YAML integer node should be loaded to a native integer data type, discarding the information that the integer was serialized in hex format.

4.3.2 Type Family Formats

Each type family used for scalar nodes has associated formats. These formats can be separated into two groups, implicit formats and explicit formats. In addition, one of the formats is designated to be the type family's canonical format.

Type families used for collection nodes do not have any associated formats.

implicit formats
A set of zero or more formats used for implicit typing. Each format may only be used in a single type family for this purpose.
explicit formats
A set of zero or more formats used for explicit typing. It is possible for two type families to share the same explicit format, though this practice is discouraged.
canonical format
In addition to the above, each scalar type family must provide a canonical format. This must be one of the implicit or explicit formats, or a subset of one of these formats. The canonical format must provide exactly one unique string representation for each possible value of the scalar.

4.3.3 Graph Node

In the graph model, each scalar node has an associated format that is one of those defined by the node's type family. Collection nodes do not have an associated format. The value of graph scalar nodes is a Unicode string that is a representation of the appropriate native value using the node's format.

4.3.4 Implicit Types and Formats

In the graph model, the type family and format are optional. When a type family or format is missing, we say that it is implicit. If a format is provided, the type family is mandatory. Since the type family is mandatory in the native model, the loader must resolve the type family and format using implicit typing. When native data is converted to YAML, the dumper is responsible for deciding which graph nodes will have explicit type family and format.

Since graph nodes may be implicitly typed, the loader may not be able to determine the type family of the node. Even when the type family is known, the loader may not have an appropriate native type. Therefore, a given YAML document need not have a native binding for every programming language or application.

4.4 Serial (Tree) Model

To allow for YAML to be communicated as a sequence of events, an ordered tree structure must be used instead of a graph. This section describes an extension to the graph model where the graph is flattened and ordered to provide a serial interface by using aliases for recurring nodes and by imposing key order. Applications constructing a native binding from the serial model should not use these extensions for the preservation of important data.

4.4.1 Serial Node

To lay out graph nodes as a tree structure, a mechanism is needed to manage duplicate occurrences. This is solved using an additional node kind, alias. The first occurrence of a node is represented using a serial node of the appropriate kind. Subsequent occurrences of either a collection or a scalar are represented by an alias node.

All nodes in the serial model have the following properties in addition to the properties defined in the graph model:

parent
The parent property gives access to the collection that contains the current serial node.
anchor
The anchor is a Unicode string that complies with the ns-ns-anchor-name production. The anchor is used to associate the first occurrence of a graph node with subsequent occurrences, via the alias serial node. This property is optional, provided that the graph node does not occur more than once in the serialization.

Note that when a serial node is converted to a graph node, the anchor, if any, is not preserved. Likewise the parent property and the alias kind are not preserved as the graph node may be contained in several collections.

4.4.2 Alias

The alias node represents subsequent occurrences of a graph node in the serialization. Like all serial nodes, an alias node has a parent and an anchor property. In addition, an anchor node has a single additional property:

referent
The serial node serial node that the alias references is the closest preceding node having the same anchor.

When an alias node is converted into a graph node it becomes a subsequent occurrence of the graph node represented by its referent node.

4.4.3 Pair

A pair is an ordered set of two serial nodes. The first member of the set is the key and the second member of the set is the value.

4.4.4 Serial Mapping

Mapping serial nodes represent the first occurrence of a mapping in a given serialization. The value of mapping serial nodes is an ordered set of node pairs.

When a mapping serial node is converted into a graph node, three operations occur. The domain is constructed with the graph node for each key in its set of pairs. Likewise, the range is constructed with the graph node for each value in its set of pairs. Last, the function is constructed via association of key graph nodes to value graph nodes, as provided by the set of pairs. Note that the ordering of the pairs is explicitly not converted.

4.4.5 Ordering

When serializing a YAML graph, every serial node is put into a single linear sequence within a given document through the mapping pair ordering. With the composition of collections, this ordering becomes total. For any two nodes or aliases, x and y we say that x precedes y when any of the following holds:

  • x is the parent of y.
  • x and y are nodes within a sequence, and x appears before y.
  • x is a key and y is a value in a given pair.
  • x and y are nodes in two pairs within a mapping, and the pair containing x comes before the pair containing y.
  • There exists a node z such that x precedes z and z precedes y.

4.5 Text (Syntax) Model

To enhance readability, a YAML serialization extends the serial model with syntax styles, comments and directives and other syntactical details. Although the parser may provide this information, applications should take care not to use these features to encode information found in a native binding.

4.5.1 Style

In the syntax, each node has an additional style property, depending on its kind.

scalar style
Scalar styles include two block styles and three flow styles. All but the double quoted style are limited to scalars having only printable characters.
collection style
There are two styles for each of the collection kinds, a block style and an flow style.

4.5.2 Comment

The syntax allows optional comment blocks to be interleaved with the node blocks. Comment blocks may appear before or after any node block. A comment block can't appear inside a scalar node value.

comment
A comment is a sequence of zero or more Unicode characters complying with the comment productions.

4.5.3 Directive

Attached to each document is a document directive section.

directive section
A collection of directives to the parser where each member of the domain and range are scalar values matching the ns-ns-directive-name and ns-ns-directive-value productions.

4.5.4 Details

The YAML syntax contains multiple mechanisms for increased readability, such as escaping, indentation, folding, line break normalization etc. While the parser may make such details available, they should not be used to encode information required for the construction of the native data.

5 Type Families

Every native node has, by definition, a type family. However this type family may be missing (implicit) from the graph model. YAML provides three mechanisms for identifying the true type family (and format) of each node.

Explicit Typing
A node may be given an explicit transfer method property, specifying the node's type family and optionally its format. If no format is given, the loader needs to select amongst the type family's formats. This is usualy done by matching the value with the regular expressions of each of the implicit and explicit formats provided by the type family to determine the specific format used.
Default Typing
When no explicit type family is given, the parser assigns the str type family to all scalar nodes, except for plain scalars. This is the only case where typing is done by the parser; all other typing is done by the loader. Specifying an explicit empty transfer method disables this and forces such nodes to undergo implicit typing.
Implicit Typing
All nodes that are not explicitly typed and do not have a default type family are subject to implicit typing. This can also be forced using the transfer indicator, '!', all by itself. The loader is then responsible for assigning a type family (and format) for such nodes. This is done in an application-specific manner. However, it is common practice to base such implicit typing on the implicit formats of scalar type families. Similarly, implicit typing of collection nodes may be based on the kind of the collection node and its contents. Implicit typing of a node may also depend on its position in the graph.

The implicit typing rules depends upon the application. It is possible to parse a document without being aware of these rules. However, without knowledge of these rules, loading an implicitly typed node to native data structures is not possible.

Following is a description of the three mandatory core type families. YAML requires support for the seq, map and str type families. YAML also provides a list of universal types that are not mandatory in the YAML type repository available at https://yaml.org/type. These types map to native data types in most programming languages or are useful in a wide range of applications. Hence applications are strongly encouraged to make use of them whenever they are appropriate in order to improve interoperability between YAML systems.

5.1 Sequence

This type family is typically used for implicitly typing sequence nodes. Example bindings include the Perl array, Python's list or tuple, and Java's array or vector.

URI:
taguri:yaml.org,2002:seq 
Shorthand:
!seq 
Definition:

Collections indexed by sequential integers starting with zero.

Kind:

Sequence.

# The following are equal seqs
# with different identities.
flow: [ one, two ]
spanning: [ one,
     two ]
block:
  - one
  - two 

5.2 Mapping

This type family is typically used for implicitly typing mapping nodes. Example bindings include the Perl hash, Python's dictionary, and Java's Hashtable.

URI:
taguri:yaml.org,2002:map 
Shorthand:
!map 
Definition:

Associative container, where each key is unique in the association and mapped to exactly one value.

Kind:

Mapping.

# The following are equal maps
# with different identities.
flow: { one: 1, two: 2 }
block:
    one: 1
    two: 2 

5.3 String

This type family is used as the default for all scalar styles with the exception of plain scalars, unless they are given an explicit transfer method property. Also, it is typically used as the default implicit type family for all plain scalars that don't match any other implicit type.

This type is usually bound to the native language's string or character array construct. Note that generic YAML tools should have an immutable (const) interface to such constructs even when the language default is mutable (such as in C/C++).

URI:
taguri:yaml.org,2002:str 
Shorthand:
!str 
Definition:

Unicode strings, a sequence of zero or more Unicode characters.

Kind:

Scalar.

Formats:
default, implicit
canonical
.* 
/* any sequence of characters */
# Assuming an application
# using implicit integers.
- 12     # An integer
- ! "12" # Also an integer.
# The following scalars
# are loaded to the
# string value '1' '2'.
- !str 12
- '12'
- "12"
- "\
 1\
 2"
# Otherwise, everything is a string:
- /foo/bar
- 192.168.1.1