diff --git a/src/table.rs b/src/table.rs index dc0fb565..c62346b7 100644 --- a/src/table.rs +++ b/src/table.rs @@ -777,16 +777,45 @@ impl Table { let mut pairs = self.pairs::().flatten().collect::>(); // Sort keys pairs.sort_by(|(a, _), (b, _)| a.sort_cmp(b)); + let is_sequence = pairs.iter().enumerate().all(|(i, (k, _))| { + if let Value::Integer(n) = k { + *n == (i + 1) as i64 + } else { + false + } + }); if pairs.is_empty() { return write!(fmt, "{{}}"); } writeln!(fmt, "{{")?; - for (key, value) in pairs { - write!(fmt, "{}[", " ".repeat(ident + 2))?; - key.fmt_pretty(fmt, false, ident + 2, visited)?; - write!(fmt, "] = ")?; - value.fmt_pretty(fmt, true, ident + 2, visited)?; - writeln!(fmt, ",")?; + if is_sequence { + // Format as list + for (_, value) in pairs { + write!(fmt, "{}", " ".repeat(ident + 2))?; + value.fmt_pretty(fmt, true, ident + 2, visited)?; + writeln!(fmt, ",")?; + } + } else { + for (key, value) in pairs { + match key { + Value::String(key) + if key + .to_string_lossy() + .chars() + .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_')) => + { + write!(fmt, "{}{}", " ".repeat(ident + 2), key.to_string_lossy())?; + write!(fmt, " = ")?; + } + _ => { + write!(fmt, "{}[", " ".repeat(ident + 2))?; + key.fmt_pretty(fmt, false, ident + 2, visited)?; + write!(fmt, "] = ")?; + } + } + value.fmt_pretty(fmt, true, ident + 2, visited)?; + writeln!(fmt, ",")?; + } } write!(fmt, "{}}}", " ".repeat(ident)) } diff --git a/tests/table.rs b/tests/table.rs index d7a425e3..d6cc90f7 100644 --- a/tests/table.rs +++ b/tests/table.rs @@ -397,6 +397,7 @@ fn test_table_fmt() -> Result<()> { .load( r#" local t = {1, 2, 3, a = 5, b = { 6 }} + t["special-"] = 10 t[9.2] = 9.2 t[1.99] = 1.99 t[true] = true @@ -410,7 +411,7 @@ fn test_table_fmt() -> Result<()> { // Pretty print assert_eq!( format!("{table:#?}"), - "{\n [false] = false,\n [true] = true,\n [1] = 1,\n [1.99] = 1.99,\n [2] = 2,\n [3] = 3,\n [9.2] = 9.2,\n [\"a\"] = 5,\n [\"b\"] = {\n [1] = 6,\n },\n}" + "{\n [false] = false,\n [true] = true,\n [1] = 1,\n [1.99] = 1.99,\n [2] = 2,\n [3] = 3,\n [9.2] = 9.2,\n a = 5,\n b = {\n 6,\n },\n [\"special-\"] = 10,\n}" ); Ok(())