From 4c3228530f5b3fb62554b9db6755e2651908e589 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Fri, 22 Apr 2016 11:29:01 +1200 Subject: [PATCH] block indent large closures somewhat rough around the edges --- src/config.rs | 8 ++++++++ src/expr.rs | 14 ++++++++++++-- src/rewrite.rs | 1 + 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index 5632e9a925c..846b8a39135 100644 --- a/src/config.rs +++ b/src/config.rs @@ -188,6 +188,12 @@ impl ConfigType for usize { } } +impl ConfigType for isize { + fn doc_hint() -> String { + String::from("") + } +} + impl ConfigType for String { fn doc_hint() -> String { String::from("") @@ -384,6 +390,8 @@ create_config! { match_block_trailing_comma: bool, false, "Put a trailing comma after a block based match arm (non-block arms are not affected)"; match_wildcard_trailing_comma: bool, true, "Put a trailing comma after a wildcard arm"; + closure_block_indent_threshold: isize, 4, "How many lines a closure must have before it is \ + block indented. -1 means never use block indent."; write_mode: WriteMode, WriteMode::Replace, "What Write Mode to use when none is supplied: Replace, Overwrite, Display, Diff, Coverage"; } diff --git a/src/expr.rs b/src/expr.rs index 248cc7e090a..2a6144481ba 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -455,9 +455,19 @@ fn rewrite_closure(capture: ast::CaptureBy, // We couldn't format the closure body as a single line expression; fall // back to block formatting. - let body_rewrite = inner_block.rewrite(&context, budget, Indent::empty()); + let body_rewrite = try_opt!(inner_block.rewrite(&context, budget, Indent::empty())); - Some(format!("{} {}", prefix, try_opt!(body_rewrite))) + let block_threshold = context.config.closure_block_indent_threshold; + if block_threshold < 0 || body_rewrite.matches('\n').count() <= block_threshold as usize { + return Some(format!("{} {}", prefix, body_rewrite)); + } + + // The body of the closure is big enough to be block indented, that means we + // must re-format. + let mut context = context.clone(); + context.block_indent.alignment = 0; + let body_rewrite = try_opt!(inner_block.rewrite(&context, budget, Indent::empty())); + Some(format!("{} {}", prefix, body_rewrite)) } fn and_one_line(x: Option) -> Option { diff --git a/src/rewrite.rs b/src/rewrite.rs index 5ca8d2e8241..247b1df1c3f 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -27,6 +27,7 @@ pub trait Rewrite { fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option; } +#[derive(Clone)] pub struct RewriteContext<'a> { pub parse_session: &'a ParseSess, pub codemap: &'a CodeMap,