From 19d933ba38e843833b9fce4776ee9b6b9f779e4e Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sat, 25 Aug 2018 13:42:40 +0300 Subject: join lines works for lambdas --- crates/libeditor/src/typing.rs | 43 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) (limited to 'crates/libeditor/src') diff --git a/crates/libeditor/src/typing.rs b/crates/libeditor/src/typing.rs index e7eba671f..060095f28 100644 --- a/crates/libeditor/src/typing.rs +++ b/crates/libeditor/src/typing.rs @@ -1,5 +1,8 @@ +use std::mem; + use libsyntax2::{ - TextUnit, TextRange, SyntaxNodeRef, File, + TextUnit, TextRange, SyntaxNodeRef, File, AstNode, + ast, algo::{ walk::preorder, find_covering_node, @@ -60,6 +63,9 @@ fn remove_newline( offset: TextUnit, ) { if node.kind() == WHITESPACE && node_text.bytes().filter(|&b| b == b'\n').count() == 1 { + if join_lambda_body(edit, node).is_some() { + return + } match (node.prev_sibling(), node.next_sibling()) { (Some(prev), Some(next)) => { let range = TextRange::from_to(prev.range().start(), node.range().end()); @@ -91,6 +97,41 @@ fn remove_newline( ); } +fn join_lambda_body( + edit: &mut EditBuilder, + node: SyntaxNodeRef, +) -> Option<()> { + let block = ast::Block::cast(node.parent()?)?; + let block_expr = ast::BlockExpr::cast(block.syntax().parent()?)?; + let _lambda = ast::LambdaExpr::cast(block_expr.syntax().parent()?)?; + let expr = single_expr(block)?; + edit.replace( + block_expr.syntax().range(), + expr.syntax().text(), + ); + Some(()) +} + +fn single_expr(block: ast::Block) -> Option { + let mut res = None; + for child in block.syntax().children() { + if let Some(expr) = ast::Expr::cast(child) { + if expr.syntax().text().contains('\n') { + return None; + } + if mem::replace(&mut res, Some(expr)).is_some() { + return None; + } + } else { + match child.kind() { + WHITESPACE | L_CURLY | R_CURLY => (), + _ => return None, + } + } + } + res +} + fn compute_ws(left: SyntaxNodeRef, right: SyntaxNodeRef) -> &'static str { match left.kind() { L_PAREN | L_BRACK => return "", -- cgit v1.2.3