1#[derive(Copy, Clone, Default)]
2pub(crate) struct DocumentFormatter {
3 pub(crate) multiline_array: bool,
4}
5
6impl toml_edit::visit_mut::VisitMut for DocumentFormatter {
7 fn visit_document_mut(&mut self, node: &mut toml_edit::Document) {
8 toml_edit::visit_mut::visit_document_mut(self, node);
9 }
10
11 fn visit_item_mut(&mut self, node: &mut toml_edit::Item) {
12 let other = std::mem::take(node);
13 let other = match other.into_table().map(toml_edit::Item::Table) {
14 Ok(i) => i,
15 Err(i) => i,
16 };
17 let other = match other
18 .into_array_of_tables()
19 .map(toml_edit::Item::ArrayOfTables)
20 {
21 Ok(i) => i,
22 Err(i) => i,
23 };
24 *node = other;
25
26 toml_edit::visit_mut::visit_item_mut(self, node);
27 }
28
29 fn visit_table_mut(&mut self, node: &mut toml_edit::Table) {
30 node.decor_mut().clear();
31
32 // Empty tables could be semantically meaningful, so make sure they are not implicit
33 if !node.is_empty() {
34 node.set_implicit(true);
35 }
36
37 toml_edit::visit_mut::visit_table_mut(self, node);
38 }
39
40 fn visit_value_mut(&mut self, node: &mut toml_edit::Value) {
41 node.decor_mut().clear();
42
43 toml_edit::visit_mut::visit_value_mut(self, node);
44 }
45
46 fn visit_array_mut(&mut self, node: &mut toml_edit::Array) {
47 toml_edit::visit_mut::visit_array_mut(self, node);
48
49 if !self.multiline_array || (0..=1).contains(&node.len()) {
50 node.set_trailing("");
51 node.set_trailing_comma(false);
52 } else {
53 for item in node.iter_mut() {
54 item.decor_mut().set_prefix("\n ");
55 }
56 node.set_trailing("\n");
57 node.set_trailing_comma(true);
58 }
59 }
60}
61