Skip to content

Formatter

Arne K. (TRC-Loop) edited this page Nov 14, 2026 · 3 revisions

Formatter

rustyon.Format pretty prints a RON document in a canonical style, like gofmt does for Go. Unlike Marshal, it works on the source text, so it keeps comments, literal spellings and the layout choices you made.

func Format(src []byte) ([]byte, error)                     // four spaces per level
func FormatIndent(src []byte, indent string) ([]byte, error) // custom indent

Both return a *SyntaxError if src is not valid RON. The output always ends with a newline. The CLI exposes the formatter as rustyon fmt.

Every before and after pair on this page is the real output of Format, and formatting each output again gives the same text.

The rules

  1. Multi line stays multi line. A collection whose elements span several lines in the input, or that contains comments, is written with one element per line, indented by one level, with trailing commas.
  2. Single line stays single line. A collection written on one line stays on one line, with , between elements, : after keys and field names, and no trailing comma.
  3. Expansion propagates outward. A collection that contains an expanded collection is expanded too.
  4. Hugging. A tuple whose only element is a collection, such as Some((...)), hugs its parent's parentheses instead of adding a level, as long as the inner collection starts on the same line.
  5. Blank lines. A single blank line between elements is kept; longer runs collapse to one.
  6. Comments are never lost. Line and block comments stay attached to the element they follow or precede. Comments in odd positions, such as between a field name and its colon, move to their own line before the element.
  7. Literals are kept verbatim: number bases, underscores, suffixes, raw strings, escapes, chars and byte strings.
  8. Extension attributes are normalized to #![enable(a, b)] on their own line.
  9. Idempotence. Format(Format(x)) equals Format(x), and the formatted document parses to an equal value.

Two details of the ron-rs grammar that the formatter keeps apart:

  • Unit and the empty tuple. () is unit and stays (). An empty tuple, written with anything between the parentheses, is printed as ( ) (( newline ) becomes ( )), so the two keep their different meaning. A named empty tuple is written Foo(): Foo( ) becomes Foo().

  • type and schema attributes. Format accepts exactly what Parse accepts, because the two share one parser. That includes #![type = "..."] and #![schema = "..."], which are kept as written, each on its own line:

    #![type = "my::T"]
    #![schema = "s.ron"]
    #![enable(implicit_some)] (a:1)

    becomes

    #![type = "my::T"]
    #![schema = "s.ron"]
    #![enable(implicit_some)]
    (a: 1)

Spacing and one line collections

Before:

Point(x:1,y:2)

After:

Point(x: 1, y: 2)

Before:

[1,2,  3,]

After (the trailing comma of a one line list is dropped):

[1, 2, 3]

Multi line collections

A single line break anywhere between elements makes the collection multi line.

Before:

{"a":1,
"b":2}

After:

{
    "a": 1,
    "b": 2,
}

The decision is made per collection. In this example the struct is multi line, but tags and pos were written on one line and stay that way:

Before:

(name:"x",
tags:[1,2,3], pos:(1,2))

After:

(
    name: "x",
    tags: [1, 2, 3],
    pos: (1, 2),
)

Expansion propagates outward. Here only the inner list was split, but the struct that contains it is expanded as well:

Before:

(a: [1,
2], b: 3)

After:

(
    a: [
        1,
        2,
    ],
    b: 3,
)

Comments

Before:

(name:"x", // the name
tags:[1,2,3])

After:

(
    name: "x", // the name
    tags: [1, 2, 3],
)

A comment inside a one line collection forces it onto several lines:

Before:

[1, /* one */ 2]

After:

[
    1, /* one */
    2,
]

Comments in unusual positions move before the element:

Before:

(a /* k */ : /* v */ 1)

After:

(
    /* k */
    /* v */
    a: 1,
)

Nested block comments are kept as they are, and comments before and after the value stay in place:

Before:

/* a /* nested */ b */ 1 // done

After:

/* a /* nested */ b */
1 // done

Trailing whitespace at the end of line comments is removed.

Hugging Some((...))

When a tuple holds exactly one collection that starts right after the opening parenthesis, the two hug:

Before After
Some((x:1,y:2)) Some((x: 1, y: 2))

If the inner collection is multi line, the hug keeps a single indentation level:

Before:

Some((
x:1,y:2))

After:

Some((
    x: 1,
    y: 2,
))

If there is a line break between the outer and inner opening parenthesis, there is no hug, and the outer tuple is expanded:

Before:

Some(
(x:1,y:2))

After:

Some(
    (x: 1, y: 2),
)

Blank lines

Before:

[
1,



2,
3]

After:

[
    1,

    2,
    3,
]

Literals and extensions

Literal spellings are never changed. The extension attribute is normalized and put on its own line:

Before:

[0xFF,1_000,r#"raw "q""#,'a',b"\x00",1e3,-inf,  "\u{1F600}"]

After:

[0xFF, 1_000, r#"raw "q""#, 'a', b"\x00", 1e3, -inf, "\u{1F600}"]

Before:

#![enable( implicit_some,unwrap_newtypes )] (a:1)

After:

#![enable(implicit_some, unwrap_newtypes)]
(a: 1)

A complete file

Before:

// Game configuration
#![enable(implicit_some)]

GameConfig( // the root
    window_size: (800, 600),
    window_title: "Rusty Game",   fullscreen: false,


    mouse_sensitivity: 1.4,
    key_bindings: {
        "up": Up, /* move up */
        // down key
        "down": Down,
        "left": Left, "right": Right
    },
    difficulty: (start: Easy, adaptive: false),
    spawn: Some((
      x: 0x10, y: 1_000,
    )),
    sprites: [ r#"raw "quoted""#, b"bytes", 'c' ],
    empty: [],
    // trailing comment in struct
)

After:

// Game configuration
#![enable(implicit_some)]

GameConfig( // the root
    window_size: (800, 600),
    window_title: "Rusty Game",
    fullscreen: false,

    mouse_sensitivity: 1.4,
    key_bindings: {
        "up": Up, /* move up */
        // down key
        "down": Down,
        "left": Left,
        "right": Right,
    },
    difficulty: (start: Easy, adaptive: false),
    spawn: Some((
        x: 0x10,
        y: 1_000,
    )),
    sprites: [r#"raw "quoted""#, b"bytes", 'c'],
    empty: [],
    // trailing comment in struct
)

Custom indentation

out, _ := rustyon.FormatIndent([]byte("[\n(a: 1,\n)]"), "\t")
fmt.Printf("%q\n", out)
// "[\n\t(\n\t\ta: 1,\n\t),\n]\n"

Errors

_, err := rustyon.Format([]byte("(a: [1, 2)"))
fmt.Println(err)
// rustyon: syntax error at 1:10: expected ',' or ']'

The formatter shares its parser with Parse, so a document is accepted by Format exactly when Parse accepts it, with the same errors. To change values in a document while keeping its comments, see Editing; Editable.Format formats an edited document.

Format versus MarshalIndent

Format MarshalIndent
Input RON text Go value
Comments kept none
Literal spellings kept (0xFF, r"...") canonical (255, "...")
Layout follows the source: one line or multi line per collection every list, map and struct on several lines; scalar tuples on one line
Trailing newline yes no

Clone this wiki locally