From c74f9018a3c5124d4780f60774858f8ac87bd4ae Mon Sep 17 00:00:00 2001 From: =?utf8?q?Jos=C3=A9=20Fonseca?= Date: Tue, 5 Apr 2011 20:54:00 +0100 Subject: [PATCH] Fix string formatting. In particular, preserve syntax highlighting when piping to 'less -R' --- trace_model.cpp | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/trace_model.cpp b/trace_model.cpp index 7f2ef44..8821417 100644 --- a/trace_model.cpp +++ b/trace_model.cpp @@ -196,7 +196,35 @@ public: } void visit(String *node) { - os << literal << '"' << node->value << '"' << normal; + os << literal << "\""; + for (std::string::const_iterator it = node->value.begin(); it != node->value.end(); ++it) { + unsigned char c = (unsigned char) *it; + if (c == '\"') + os << "\\\""; + else if (c == '\\') + os << "\\\\"; + else if (c >= 0x20 && c <= 0x7e) + os << c; + else if (c == '\t') { + os << "\t"; + } else if (c == '\r') { + // Ignore carriage-return + } else if (c == '\n') { + // Reset formatting so that it looks correct with 'less -R' + os << normal << '\n' << literal; + } else { + unsigned octal0 = c & 0x7; + unsigned octal1 = (c >> 3) & 0x7; + unsigned octal2 = (c >> 3) & 0x7; + os << "\\"; + if (octal2) + os << octal2; + if (octal1) + os << octal1; + os << octal0; + } + } + os << "\"" << normal; } void visit(Enum *node) { -- 2.45.2