diff --git a/src/lib.rs b/src/lib.rs index fae8080c02e..e5164d56eee 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -396,37 +396,40 @@ fn format_code_block( .unwrap_or_else(|| formatted.snippet.len()); let mut is_indented = true; let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config); - for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) { - if !is_first { - result.push('\n'); - } else { - is_first = false; - } - let trimmed_line = if !is_indented { - line - } else if line.len() > config.max_width() { - // If there are lines that are larger than max width, we cannot tell - // whether we have succeeded but have some comments or strings that - // are too long, or we have failed to format code block. We will be - // conservative and just return `None` in this case. - return None; - } else if line.len() > indent_str.len() { - // Make sure that the line has leading whitespaces. - if line.starts_with(indent_str.as_ref()) { - let offset = if config.hard_tabs() { - 1 + + if let Some(to_format) = formatted.snippet.get(FN_MAIN_PREFIX.len()..block_len) { + for (kind, ref line) in LineClasses::new(to_format) { + if !is_first { + result.push('\n'); + } else { + is_first = false; + } + let trimmed_line = if !is_indented { + line + } else if line.len() > config.max_width() { + // If there are lines that are larger than max width, we cannot tell + // whether we have succeeded but have some comments or strings that + // are too long, or we have failed to format code block. We will be + // conservative and just return `None` in this case. + return None; + } else if line.len() > indent_str.len() { + // Make sure that the line has leading whitespaces. + if line.starts_with(indent_str.as_ref()) { + let offset = if config.hard_tabs() { + 1 + } else { + config.tab_spaces() + }; + &line[offset..] } else { - config.tab_spaces() - }; - &line[offset..] + line + } } else { line - } - } else { - line - }; - result.push_str(trimmed_line); - is_indented = indent_next_line(kind, line, config); + }; + result.push_str(trimmed_line); + is_indented = indent_next_line(kind, line, config); + } } Some(FormattedSnippet { snippet: result, diff --git a/tests/target/issue-5234.rs b/tests/target/issue-5234.rs new file mode 100644 index 00000000000..f0db02650de --- /dev/null +++ b/tests/target/issue-5234.rs @@ -0,0 +1,14 @@ +// rustfmt-format_code_in_doc_comments: true + +/// ``` +/// ``` +fn a() {} + +/// ``` +/// ``` +fn a() {} + +/// ```rust +/// k1 == k2 ⇒ hash(k1) == hash(k2) +/// ``` +pub struct a;