Joe
Joe

Reputation: 6816

Is it possible set the base level of Emitter indentation in yaml-cpp?

Is there a one-time way to set the base level of indentation for all values that Emitter emits in yaml-cpp?

I tried using Emitter::SetIndent and Emitter::SetLocalIndent but those only seem to affect items below the root level of the emitter, not root level items themselves

To illustrate, consider the following, desired YAML output. Values start off indented by 4 spaces already (my comments to the right are not part of the output)

    type: Circle            // Correctly indented by 1 level (4 spaces)
    r: 492.763875219
    x: 1286.75555556
    y: 1195.04
    regions:
      - id: 1750272850      // Correctly indented by 2 levels (8 spaces)
        width: 200
      - id: 524770566
        width: 42

I tried to write it out with this code:

void Shape::writeToYaml(std::ostream& os)
{
    YAML::Emitter out;      
    out.SetIndent(4);         // THIS DOES NOT HELP
    out << YAML::BeginMap;

    for (auto&& prop : properties())   // 'properties()' returns std::map<string, string>
        out << YAML::Key << prop.first << YAML::Value << prop.second;
    out << YAML::Key << PK_REGIONS << YAML::Value;
    out << YAML::BeginSeq; 
    for (auto&& region : m_regions)
        out << region.properties();  // 'properties()' returns std::map<string, string>

    out << YAML::EndSeq;
    out << YAML::EndMap;

    os << out.c_str();
}

Instead I got this output where the root values are not indented at all and the values below those are indented by too much

type:   Circle                         // WRONG: NOT INDENTED AT ALL
r:      492.763875219
x:      1286.75555556
y:      1195.04
regions:
        -       id:     2077164443     // WRONG: INDENTED BY TOO MUCH
                width:  200
        -       id:     2031385931
                width:  42

(I'm trying to adapt existing yaml-writing code without exposing yaml-cpp types in my API, so I need to be able to create Emitters on the fly and then just set their base indentation. I'm using the latest, 0.6 version, downloaded yesterday)

Upvotes: 0

Views: 368

Answers (1)

flyx
flyx

Reputation: 39738

afaik yaml-cpp can't do this for you, but the workaround is quite simple:

std::stringstream ss(out.c_str());
std::string line;
while (std::getline(line, ss)) {
  os << "    " << line << std::endl;
}

To avoid copying the emitter's output string, see here.

Upvotes: 1

Related Questions