---
title: "Remove a YAML key and keep its leading comments in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/remove-yaml-key-keep-leading-comments/
description: "Remove a YAML mapping entry in Rust while keeping the comment above it, and inspect the inline comment that was removed with the entry."
version: "1.2.0"
---

# Remove a YAML key and keep its leading comments in Rust

**oneyaml** is a free, open-source YAML library for Rust from Recursive AI. MIT or Apache-2.0, no unsafe code.

[crates.io](https://crates.io/crates/oneyaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-rust) · [Docs](https://recursiveai.org/oneyaml/rust/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/rust/cookbook/remove-yaml-key-keep-leading-comments/remove-yaml-key-keep-leading-comments.zip)

Use `remove_keep_comments` to keep the note above a deleted key, but not the inline comment.

```shell
cargo add oneyaml
```

```rust
use oneyaml::{Document, path};

fn main() {
    let yaml = concat!(
        "web:\n  port: 8080\n",
        "  # Proxy settings\n",
        "  old_proxy: off # retired\n",
        "  proxy: ready\n",
    );
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    let id = doc.id_of(&path!["web", "old_proxy"])
        .expect("old_proxy entry");
    let removed = doc.remove_keep_comments(id)
        .expect("removable entry");
    print!("{doc}");
    println!("Removed: {:?}",
        removed.comments());
}
```

Unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/remove-yaml-key-keep-leading-comments/remove-yaml-key-keep-leading-comments.zip), then `cargo run`.

Requires Rust 1.85 or later.

```text
web:
  port: 8080
  # Proxy settings
  proxy: ready
Removed: ["# retired"]
```

## The full program

The sample input is inline. The program prints the edited YAML and the comments returned with the removed entry. It also tries ordinary removal on a fresh copy of the same input. If the leading comment can’t attach to the next entry or as a footer, the keep-comments edit returns an error and changes nothing.

```rust
use oneyaml::{Document, path};

fn main() {
    let yaml = concat!(
        "web:\n  port: 8080\n",
        "  # Proxy settings\n",
        "  old_proxy: off # retired\n",
        "  proxy: ready\n",
    );
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    let id = doc.id_of(&path!["web", "old_proxy"])
        .expect("old_proxy entry");
    let removed = doc.remove_keep_comments(id)
        .expect("removable entry");
    print!("{doc}");
    println!("Removed: {:?}",
        removed.comments());

    let mut doc = Document::parse(yaml).expect("valid YAML");
    let id = doc.id_of(&path!["web", "old_proxy"])
        .expect("old_proxy entry");
    let removed = doc.remove_node(id).expect("removable entry");
    println!("Removed normally: {:?}", removed.comments());
}
```

`cargo run` prints:

```text
web:
  port: 8080
  # Proxy settings
  proxy: ready
Removed: ["# retired"]
Removed normally: ["# Proxy settings", "# retired"]
```

## Variations

To edit a file, save the inline sample YAML as `config.yaml`. Replace the inline `yaml` declaration in the snippet at the top with the read below, and pass `&yaml` to `Document::parse`. Add the write after `remove_keep_comments` succeeds. The original file stays unchanged.

```rust
let yaml = std::fs::read_to_string("config.yaml").expect("read config.yaml");
// Parse &yaml and remove the entry as shown above.
std::fs::write("updated.yaml", doc.to_string()).expect("write updated.yaml");
```

## Related recipes

- [Edit YAML and keep its comments](https://recursiveai.org/oneyaml/rust/cookbook/edit-yaml-keep-comments/)
- [Patch YAML in Rust](https://recursiveai.org/oneyaml/rust/cookbook/patch-yaml/)
- [Read the comment attachment rules](https://recursiveai.org/oneyaml/rust/docs/comment-attachment/)

## The short answer

Parse the source as a `Document`, look up the mapping entry with `id_of`, and call `remove_keep_comments`. In the example, `# Proxy settings` stays in the YAML above `proxy: ready`, while `# retired` leaves with `old_proxy`. The method returns a `Removed`, whose `comments()` lets you see what was taken out. For a file edit, the text to write back is `doc.to_string()`, not the removed entry.

## How do you preserve comments when removing a YAML key?

First decide whether the comment describes the disappearing key or the section around it. The note in the example describes the whole proxy section, so it belongs in the file after `old_proxy` is gone. The same-line note describes only the retired setting, so it goes with it. Use `remove_keep_comments` when that split is what you want. Use `remove_node` if the leading note would be misleading above the next setting.

Pass the path to the key to `id_of`, as in `path!["web", "old_proxy"]`. You don’t need to find the token `old_proxy` yourself or remove the line with a string replacement. The [method documentation](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/document/edit.rs#L7326-L7341) also distinguishes leading comments written above the entry from comments inside it. Notes inside the entry go out with it, as does the same-line note.

## Where do comments go when you remove the last YAML key?

There’s no next key to own the note. When an entry is last in a nested collection, the retained leading lines become a footer for that collection; when it’s last at the root, they become the document footer. The [pinned examples](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/tests/comment_edits.rs#L62-L103) show both cases. The note stays in the file but no longer describes a following entry.

If you remove the only entry of a collection with leading comments, or try this on an entry with leading comments in a flow collection (written with braces or brackets), there may be no valid new owner. The [method’s error documentation](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/document/edit.rs#L7362-L7368) specifies `Unsupported` for those cases and `CommentReattaches` when a note would attach somewhere other than intended. Handle the error before saving. If the comment needs to become a section note in a different location, make that a separate edit rather than assuming the library can keep it where the entry was.
