diff --git a/src/lib.rs b/src/lib.rs index 6fc3dc859455..35f0cba26a89 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,10 +50,11 @@ use crate::comment::LineClasses; use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile}; use crate::issues::Issue; use crate::shape::Indent; +use crate::utils::indent_next_line; pub use crate::config::{ load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle, - Range, Verbosity, + Range, Verbosity, Version, }; #[macro_use] @@ -438,7 +439,7 @@ fn format_code_block(code_snippet: &str, config: &Config) -> Option Option Some(get_prefix_space_width(config, &line)) }; - let new_veto_trim_value = (kind.is_string() - || (config.version() == Version::Two && kind.is_commented_string())) + // just InString{Commented} in order to allow the start of a string to be indented + let new_veto_trim_value = (kind == FullCodeCharKind::InString + || (config.version() == Version::Two + && kind == FullCodeCharKind::InStringCommented)) && !line.ends_with('\\'); let line = if veto_trim || new_veto_trim_value { veto_trim = new_veto_trim_value; @@ -574,6 +576,13 @@ pub fn trim_left_preserve_layout(orig: &str, indent: Indent, config: &Config) -> ) } +/// Based on the given line, determine if the next line can be indented or not. +/// This allows to preserve the indentation of multi-line literals. +pub fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool { + !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string())) + || line.ends_with('\\') +} + pub fn is_empty_line(s: &str) -> bool { s.is_empty() || s.chars().all(char::is_whitespace) } diff --git a/tests/source/issue-3302.rs b/tests/source/issue-3302.rs new file mode 100644 index 000000000000..c037584fd710 --- /dev/null +++ b/tests/source/issue-3302.rs @@ -0,0 +1,43 @@ +// rustfmt-version: Two + +macro_rules! moo1 { + () => { + bar! { +" +" + } + }; +} + +macro_rules! moo2 { + () => { + bar! { + " +" + } + }; +} + +macro_rules! moo3 { + () => { + 42 + /* + bar! { + " + toto +tata" + } + */ + }; +} + +macro_rules! moo4 { + () => { + bar! { +" + foo + bar +baz" + } + }; +} diff --git a/tests/target/issue-3302.rs b/tests/target/issue-3302.rs new file mode 100644 index 000000000000..146cb9838193 --- /dev/null +++ b/tests/target/issue-3302.rs @@ -0,0 +1,43 @@ +// rustfmt-version: Two + +macro_rules! moo1 { + () => { + bar! { + " +" + } + }; +} + +macro_rules! moo2 { + () => { + bar! { + " +" + } + }; +} + +macro_rules! moo3 { + () => { + 42 + /* + bar! { + " + toto +tata" + } + */ + }; +} + +macro_rules! moo4 { + () => { + bar! { + " + foo + bar +baz" + } + }; +}