From e90b0868aa2ee46e11b42f0a4fea5db3be32df92 Mon Sep 17 00:00:00 2001 From: q66 Date: Sat, 25 Feb 2017 17:33:18 +0100 Subject: [PATCH] make the dash flag toggle current escaping mode in format --- examples/format.cc | 17 +++++++++++++---- ostd/format.hh | 13 ++++++++++++- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/examples/format.cc b/examples/format.cc index a429271..e5ad782 100644 --- a/examples/format.cc +++ b/examples/format.cc @@ -75,7 +75,7 @@ int main() { * items are escaped automatically (strings and chars) */ writefln("{ %#(%s: %d, %) }", m); - /* the - flag overrides escaping, so you get { baz: 15, bar: 10, foo: 5} */ + /* the - flag toggles escaping, so you get { baz: 15, bar: 10, foo: 5} */ writefln("{ %-#(%s: %d, %) }", m); /* no expansion of the items, print entire tuple with default format, * gets you something like { <"baz", 15>, <"bar", 10>, <"foo", 5> } @@ -83,12 +83,21 @@ int main() { */ writefln("{ %(%s, %) }", m); + /* as the - flag toggles escaping on strings and chars, when auto-escape + * is turned on for some reason, you can toggle it for specific items, + * and you can even manually force escaping on things + */ + writefln("not escaped: %s, escaped: %-s", "foo", "bar"); + /* you can expand tuples similarly to ranges, with % where * CONTENTS is a regular format string like if the tuple was formatted - * separately with each item of the tuple passed as a separate argument + * separately with each item of the tuple passed as a separate argument, + * keep in mind that this auto-escapes strings/chars just like ranges */ - std::tuple tup{"hello world", 1337, 3.14f}; - writefln("the tuple contains %<%s, %d, %f%>.", tup); + std::tuple tup{ + "hello world", 1337, 3.14f, "test" + }; + writefln("the tuple contains %<%s, %d, %f, %-s%>.", tup); /* formatting a range of tuples, with each tuple expanded * with a nested tuple expansion inside a range expansion diff --git a/ostd/format.hh b/ostd/format.hh index 6196003..22fa8c3 100644 --- a/ostd/format.hh +++ b/ostd/format.hh @@ -319,7 +319,12 @@ private: bool read_spec_range(bool tuple = false) { int sflags = p_flags; - p_nested_escape = !(sflags & FMT_FLAG_DASH); + /* printing ranges or tuples toggles escaping mode by default, + * but as the dash flag also toggles, it means no change + */ + if (!(sflags & FMT_FLAG_DASH)) { + p_nested_escape = !p_nested_escape; + } p_fmt.pop_front(); string_range begin_inner(p_fmt); if (!read_until_dummy()) { @@ -486,6 +491,9 @@ private: if (has_precision()) { n = std::min(n, size_t(precision())); } + if (p_flags & FMT_FLAG_DASH) { + escape = !escape; + } write_spaces(writer, n, true); if (escape) { writer.put('"'); @@ -512,6 +520,9 @@ private: /* char values */ template void write_char(R &writer, bool escape, char val) const { + if (p_flags & FMT_FLAG_DASH) { + escape = !escape; + } if (escape) { char const *esc = detail::escape_fmt_char(val, '\''); if (esc) {