pub fn tidy(source: &str) -> Result<String, Error>Expand description
Lays a form’s indentation out again, and changes nothing else.
Not a canonical formatter. kdl’s own
(autoformat)
is one, and it deletes a comment written at the end of a node’s line
(#119,
kdl-org/kdl-rs#179) — which
is not a thing to ship into a format whose first promise is that comments
survive. It also unquotes strings and drops blank lines.
So this does the one thing hand-editing actually breaks and nothing else: only the whitespace at the two ends of a line is ever touched. Comments keep their text and their position, strings keep their quoting, properties keep their order, blank lines stay blank lines, and columns lined up by hand inside a line stay lined up. What changes is the indent in front of each line, to one step per level of nesting, and trailing whitespace, which goes.
The step is the file’s own — whatever the first node inside form uses — so
a file written with two spaces stays a two-space file. Four spaces is the
fallback for a file that does not say.
Lines inside a multi-line string or a block comment are left exactly as they are, because those are content rather than layout.
let ragged = "\
form \"F\" version=1 width=20 height=20 {
label \"one\" x=0 y=0 w=5 h=5 // kept, and still here
label \"two\" x=0 y=6 w=5 h=5
}
";
let tidied = tidy(ragged)?;
assert_eq!(tidied, "\
form \"F\" version=1 width=20 height=20 {
label \"one\" x=0 y=0 w=5 h=5 // kept, and still here
label \"two\" x=0 y=6 w=5 h=5
}
");Refuses a file it cannot parse, because a formatter that rewrites what it does not understand is how a file gets lost.