Fix formatting block string containing quotes

Single-line block strings are parsed as PlainLines. When the string
contains quotes, this leads to invalid formatted strings. This commit
special cases strings containing quotes the same as strings containing
newlines and formats them to multiple lines using triple-quotes.
This commit is contained in:
raleng 2022-08-26 11:36:54 +02:00
parent 4991adb05b
commit 1c8bc7d969
No known key found for this signature in database
GPG key ID: A7DBF700E0E77020

View file

@ -484,24 +484,20 @@ pub fn fmt_str_literal<'buf>(buf: &mut Buf<'buf>, literal: StrLiteral, indent: u
buf.push('"');
match literal {
PlainLine(string) => {
// When a PlainLine contains "\n" it is formatted as a block string using """
let mut lines = string.split('\n');
match (lines.next(), lines.next()) {
(Some(first), Some(second)) => {
buf.push_str("\"\"");
buf.newline();
for line in [first, second].into_iter().chain(lines) {
buf.indent(indent);
buf.push_str_allow_spaces(line);
buf.newline();
}
// When a PlainLine contains '\n' or '"', format as a block string
if string.contains('"') || string.contains('\n') {
buf.push_str("\"\"");
buf.newline();
for line in string.split('\n') {
buf.indent(indent);
buf.push_str("\"\"");
buf.push_str_allow_spaces(line);
buf.newline();
}
_ => buf.push_str_allow_spaces(string),
}
buf.indent(indent);
buf.push_str("\"\"");
} else {
buf.push_str_allow_spaces(string);
};
}
Line(segments) => {
for seg in segments.iter() {