From 18918769baf49acc4067eabdc0c3a0a98224d23f Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Thu, 23 Aug 2018 21:38:25 +0300 Subject: Smarter join lines --- crates/libeditor/src/lib.rs | 2 +- crates/libeditor/src/typing.rs | 31 +++++++++++++++++++++++++++++++ crates/libeditor/tests/test.rs | 4 ++-- 3 files changed, 34 insertions(+), 3 deletions(-) (limited to 'crates') diff --git a/crates/libeditor/src/lib.rs b/crates/libeditor/src/lib.rs index f8bc73ae9..b29603da3 100644 --- a/crates/libeditor/src/lib.rs +++ b/crates/libeditor/src/lib.rs @@ -12,7 +12,7 @@ mod typing; use libsyntax2::{ ast::{self, NameOwner}, AstNode, - algo::{walk, find_leaf_at_offset, find_covering_node}, + algo::{walk, find_leaf_at_offset}, SyntaxKind::{self, *}, }; pub use libsyntax2::{ParsedFile, TextRange, TextUnit}; diff --git a/crates/libeditor/src/typing.rs b/crates/libeditor/src/typing.rs index f49dd0fdc..918f2325c 100644 --- a/crates/libeditor/src/typing.rs +++ b/crates/libeditor/src/typing.rs @@ -5,6 +5,7 @@ use libsyntax2::{ walk::preorder, find_covering_node, }, + SyntaxKind::*, }; use {ActionResult, EditBuilder}; @@ -68,6 +69,24 @@ fn remove_newline( node_text: &str, offset: TextUnit, ) { + if node.kind() == WHITESPACE && node_text.bytes().filter(|&b| b == b'\n').count() == 1 { + match (node.prev_sibling(), node.next_sibling()) { + (Some(prev), Some(next)) => { + if prev.kind() == COMMA && (next.kind() == R_PAREN || next.kind() == R_BRACK) { + let range = TextRange::from_to(prev.range().start(), node.range().end()); + edit.delete(range); + } else { + edit.replace( + node.range(), + compute_ws(prev, next).to_string(), + ); + } + return; + } + _ => (), + } + } + let suff = &node_text[TextRange::from_to( offset - node.range().start() + TextUnit::of_char('\n'), TextUnit::of_str(node_text), @@ -79,3 +98,15 @@ fn remove_newline( " ".to_string(), ); } + +fn compute_ws(left: SyntaxNodeRef, right: SyntaxNodeRef) -> &'static str { + match left.kind() { + L_PAREN | L_BRACK => return "", + _ => (), + } + match right.kind() { + R_PAREN | R_BRACK => return "", + _ => (), + } + " " +} diff --git a/crates/libeditor/tests/test.rs b/crates/libeditor/tests/test.rs index 6aa260a86..e5088ad27 100644 --- a/crates/libeditor/tests/test.rs +++ b/crates/libeditor/tests/test.rs @@ -195,7 +195,7 @@ fn foo() { } ", r" fn foo() { - <|>foo(1, ) + <|>foo(1) } "); } @@ -221,7 +221,7 @@ fn foo() { } ", r" fn foo() { - foo(1, 2, 3, ) + foo(1, 2, 3) } "); } -- cgit v1.2.3