Skip to content

Editing

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

Editing

rustyon.ParseEditable opens a RON document for in-place edits that keep everything you did not touch: comments, number spellings, blank lines and indentation. It is the tool for programs that change a hand-written config file (set a port, add a user, delete an unused key) without turning it into a canonically formatted copy, which is what Unmarshal followed by Marshal would do.

func ParseEditable(src []byte) (*Editable, error)

func (e *Editable) Get(path string) (Value, bool)
func (e *Editable) Set(path string, v Value) error
func (e *Editable) SetRON(path, ron string) error
func (e *Editable) Delete(path string) error
func (e *Editable) Insert(path string, i int, v Value) error
func (e *Editable) Append(path string, v Value) error
func (e *Editable) Bytes() []byte
func (e *Editable) String() string
func (e *Editable) Format(indent string) []byte
func (e *Editable) Extensions() Extensions

var ErrPathNotFound error

ParseEditable accepts exactly the documents Parse accepts and returns a *SyntaxError otherwise. An Editable is not safe for concurrent use.

Every example on this page uses this document, and the output shown is the real output:

const src = `// server settings
(
    host: "localhost", // where to listen
    port: 8080,
    users: ["ann", "bob"],
    limits: {"cpu": 2, "mem": 512},
    tls: Some((cert: "a.pem")),
)`

doc, err := rustyon.ParseEditable([]byte(src))

Paths

Paths use the same syntax as rustyon get in the CLI.

Path Selects
port the field port of a struct, or a map entry whose key is the string or identifier port
.limits.cpu a leading dot is optional; nested names are joined with dots
users[0] element 0 of a list or tuple, or the map entry with the integer key 0
users[-1] negative indexes count from the end of a list or tuple
limits["cpu"] a map entry with the string key "cpu" (or an identifier key cpu), or a struct field
"" or . the whole document value

Other rules:

  • Some(x) is looked through: with tls: Some((cert: "a.pem")), the path tls.cert addresses the cert field inside. None has nothing to step into.
  • A name step must not be empty and cannot contain ., [ or ]. Use ["a.b"] for a key with a dot in it.
  • A path addresses a node. Set("tls", ...) replaces all of Some((cert: "a.pem")), not just its content.
  • Raw identifier fields (r#type) are addressed without the r#: type.
for _, p := range []string{"port", "users[0]", "users[-1]", `limits["cpu"]`, "limits.mem", "tls.cert", "nope", "users[5]"} {
    v, ok := doc.Get(p)
    fmt.Printf("%q -> %v %v\n", p, v, ok)
}
// "port" -> 8080 true
// "users[0]" -> ann true
// "users[-1]" -> bob true
// "limits[\"cpu\"]" -> 2 true
// "limits.mem" -> 512 true
// "tls.cert" -> a.pem true
// "nope" -> <nil> false
// "users[5]" -> <nil> false

Get

Get returns the Value at a path, parsed from the current text, so it sees all edits made so far. It reports false when the path is malformed or selects nothing; use Set or Delete if you need the reason as an error.

v, _ := doc.Get("users")
fmt.Printf("%T %v\n", v, v)
// rustyon.List [ann bob]

Set

Set(path, v) replaces the value at path with a Value. The new value is written on one line, in the canonical style of Marshal. Comments around the old value stay; comments inside the old value go with it.

If the last step of the path names something that does not exist, it is added: a new field at the end of a struct (also of () and Name()), or a new entry at the end of a map. A new map key is written as an identifier when the existing keys are identifiers, and as a string otherwise. A step [N] adds the integer key N.

doc.Set("port", rustyon.NewInt(9090))
doc.Set("users[0]", rustyon.String("zed"))
doc.Set("limits.cpu", rustyon.NewInt(4))
doc.Set("debug", rustyon.Bool(true))               // new struct field
doc.Set(`limits["disk"]`, rustyon.NewInt(10))      // new map entry
fmt.Println(doc)
// // server settings
// (
//     host: "localhost", // where to listen
//     port: 9090,
//     users: ["zed", "bob"],
//     limits: {"cpu": 4, "mem": 512, "disk": 10},
//     tls: Some((cert: "a.pem")),
//     debug: true,
// )

Adding works on the last step only. Every parent must exist, so Set("new.deep", v) fails with ErrPathNotFound instead of creating new. Set cannot add an element to a list or tuple; use Insert or Append.

d, _ := rustyon.ParseEditable([]byte("{a: 1, b: 2}"))
d.Set("c", rustyon.NewInt(3))
d.Set("[7]", rustyon.NewInt(3))
fmt.Println(d)
// {a: 1, b: 2, c: 3, 7: 3}

d, _ = rustyon.ParseEditable([]byte("Config()"))
d.Set("a", rustyon.NewInt(1))
fmt.Println(d)
// Config(a: 1)

Set with an empty path replaces the whole document value.

Build values with the constructors of the Value Tree. To write None or an enum variant, use SetRON (a rustyon.Ident("None") is written as the raw identifier r#None, which is not the None of Option).

SetRON

SetRON(path, ron) is Set with the new value given as RON text. The text is inserted as written, so you control number bases, suffixes, raw strings and even line breaks. It must be exactly one value, with no comments around it, and it must be valid where it is inserted: Some 1 is invalid, and a plain 5 for an option only works if the document enables implicit_some.

d, _ := rustyon.ParseEditable([]byte("(color: 255, range: 1..3, // c\n name: \"x\")"))
d.SetRON("color", "0xFF_u8")
d.SetRON("range", "0x10..=0x20")
d.SetRON("name", `r#"raw"#`)
fmt.Println(d)
// (color: 0xFF_u8, range: 0x10..=0x20, // c
//  name: r#"raw"#)

fmt.Println(d.SetRON("name", "1 2"))
// rustyon: invalid value "1 2": expected a single value
fmt.Println(d.SetRON("name", "// c\n1"))
// rustyon: invalid value "// c\n1": rustyon: syntax error at 1:1: unexpected character '/'

d, _ = rustyon.ParseEditable([]byte("#![enable(implicit_some)]\n(a: None)"))
d.SetRON("a", "5")
fmt.Println(d)
// #![enable(implicit_some)]
// (a: 5)

Ranges cannot be built as a Value, so SetRON is also the way to write one.

Delete

Delete(path) removes the value together with its field name or map key. The comments directly above the element (with no blank line between) and the comments after it on its line go with it. All other comments stay. Deleting the last element leaves an empty collection. Deleting the whole document (empty path) is an error.

doc.Delete("port")
doc.Delete("users[0]")
doc.Delete(`limits["mem"]`)
fmt.Println(doc)
// // server settings
// (
//     host: "localhost", // where to listen
//     users: ["bob"],
//     limits: {"cpu": 2},
//     tls: Some((cert: "a.pem")),
// )

The comment rule in detail. Here // about a and // trailing belong to a and are removed, but // about b is separated from b by a blank line and stays:

d, _ := rustyon.ParseEditable([]byte("(\n    // about a\n    a: 1, // trailing\n\n    // about b\n\n    b: 2,\n)"))
d.Delete("a")
fmt.Println(d)
// (
//
//     // about b
//
//     b: 2,
// )

d, _ = rustyon.ParseEditable([]byte("[1]"))
d.Delete("[0]")
fmt.Println(d)
// []

Insert and Append

Insert(path, i, v) puts v into the list at path so that it ends up at index i (0 to the length of the list). Append adds at the end. The new element follows the layout of its neighbors: on its own line when the list is written one element per line, inline otherwise. Comments stay with the elements they belong to, so an inserted element goes above the comment of the element it displaces.

d, _ := rustyon.ParseEditable([]byte("[\n    1,\n    // three\n    3,\n]"))
d.Insert("", 1, rustyon.NewInt(2))
d.Append("", rustyon.NewInt(4))
fmt.Println(d)
// [
//     1,
//     2,
//     // three
//     3,
//     4,
// ]

d, _ = rustyon.ParseEditable([]byte(`(tags: ["a", "b"])`))
d.Append("tags", rustyon.String("c"))
d.Insert("tags", 0, rustyon.String("z"))
fmt.Println(d)
// (tags: ["z", "a", "b", "c"])

d, _ = rustyon.ParseEditable([]byte("(tags: [])"))
d.Append("tags", rustyon.String("c"))
fmt.Println(d)
// (tags: ["c"])

Insert and Append only work on lists. A tuple, a map or a scalar at the path gives an error, and so does an index outside 0..len.

Bytes, String, Format, Extensions

  • Bytes() and String() return the current document text.
  • Extensions() returns the extensions enabled by the document's #![enable(...)] attributes (see Extensions).
  • Format(indent) returns the document reformatted like FormatIndent, with all comments kept. It does not change the Editable.
d, _ := rustyon.ParseEditable([]byte("#![enable(implicit_some)]\n(a: 1)"))
fmt.Printf("%q %v\n", d.String(), d.Extensions().Names())
// "#![enable(implicit_some)]\n(a: 1)" [implicit_some]

d, _ = rustyon.ParseEditable([]byte("(a:1, // x\nb:[1,2])"))
d.Set("a", rustyon.NewInt(2))
fmt.Printf("%s\n%s", d, d.Format("  "))
// (a:2, // x
// b:[1,2])
// (
//   a: 2, // x
//   b: [1, 2],
// )

A typical program edits, then writes doc.Bytes() back to the file, optionally via Format for a normalized layout.

What is preserved

An edit is a text change at the place the path selects. Everything else is kept byte for byte: comments, number spellings (0xFF, 1_000), raw strings, blank lines, indentation, the #![enable(...)] attributes and the spelling of struct names. CRLF line endings and a leading byte order mark are kept too. The text you insert is the only thing in canonical style (Set, Insert, Append), or is exactly what you wrote (SetRON).

New fields, map entries and list elements copy the indentation of their neighbors, and the indentation unit is guessed from the first indented line of the document (four spaces if there is none).

After every edit the whole result is parsed again. If the edit would produce an invalid document, the Editable is left unchanged and an error is returned, so the text of a successful Editable is always valid RON.

Errors

Errors for a path that does not select anything wrap rustyon.ErrPathNotFound, so test them with errors.Is. The message names the step that failed.

err := doc.Set("limits.cpu.x", rustyon.NewInt(1))
fmt.Println(err, errors.Is(err, rustyon.ErrPathNotFound))
// rustyon: path not found: .limits.cpu.x: a scalar has no field or key "x" true

err = doc.Delete("nope")
fmt.Println(err, errors.Is(err, rustyon.ErrPathNotFound))
// rustyon: path not found: .nope true

err = doc.Set("users[2]", rustyon.NewInt(1))
fmt.Println(err, errors.Is(err, rustyon.ErrPathNotFound))
// rustyon: path not found: .users[2]: index 2 out of range, length 2 true

err = doc.Set("new.deep", rustyon.NewInt(1))
fmt.Println(err, errors.Is(err, rustyon.ErrPathNotFound))
// rustyon: path not found: .new true

d, _ := rustyon.ParseEditable([]byte("(a: None)"))
fmt.Println(d.Set("a.b", rustyon.NewInt(1)))
// rustyon: path not found: .a.b: value is None

Other errors do not wrap ErrPathNotFound:

Call Error
a malformed path, such as a..b invalid path "a..b": empty name at offset 2
Delete("") rustyon: cannot delete the document value
Append("port", v) where port is not a list rustyon: port is not a list
Insert("users", 9, v) rustyon: index 9 out of range, length 2
Set("b c", v) adding a field whose name is not an identifier rustyon: "b c" is not a valid field name
SetRON with text that is not one valid value rustyon: invalid value "(": rustyon: syntax error at 1:2: unexpected end of input
an edit that makes the document invalid rustyon: the edit would produce an invalid document: ...

Limitations

  • Set values are written inline. Set, Insert and Append write the new value on one line, even a big list or struct. Use SetRON for a multi-line value, or call Format afterwards.
  • Ranges are not addressable. A range such as 1..3 is a single node: you can replace it as a whole (with SetRON), but r.start selects nothing.
  • Only string, identifier and integer map keys are addressable. Entries with keys such as (1, 2), 1.5 or 'c' cannot be reached by a path, so they cannot be read, replaced or deleted individually. Other entries of the same map are not affected.
  • Lists and tuples cannot grow through Set. Use Insert and Append, which only work on lists.
  • Comment attachment is positional. Only comments directly above or after an element on its line are treated as belonging to it. A comment separated by a blank line is kept when the element is deleted.
  • Values are not interpreted. An Editable knows RON structure, not your Go types. Changing a value to the wrong type is only noticed when you later Unmarshal the document.

See also: Formatter for reformatting whole documents, Value Tree for the Value types, and CLI for the same path syntax in rustyon get.

Clone this wiki locally