Smarter join lines

This commit is contained in:
Aleksey Kladov 2018-08-23 21:38:25 +03:00
parent 6dcf87fb5f
commit 18918769ba
3 changed files with 34 additions and 3 deletions

View file

@ -12,7 +12,7 @@ mod typing;
use libsyntax2::{ use libsyntax2::{
ast::{self, NameOwner}, ast::{self, NameOwner},
AstNode, AstNode,
algo::{walk, find_leaf_at_offset, find_covering_node}, algo::{walk, find_leaf_at_offset},
SyntaxKind::{self, *}, SyntaxKind::{self, *},
}; };
pub use libsyntax2::{ParsedFile, TextRange, TextUnit}; pub use libsyntax2::{ParsedFile, TextRange, TextUnit};

View file

@ -5,6 +5,7 @@ use libsyntax2::{
walk::preorder, walk::preorder,
find_covering_node, find_covering_node,
}, },
SyntaxKind::*,
}; };
use {ActionResult, EditBuilder}; use {ActionResult, EditBuilder};
@ -68,6 +69,24 @@ fn remove_newline(
node_text: &str, node_text: &str,
offset: TextUnit, 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( let suff = &node_text[TextRange::from_to(
offset - node.range().start() + TextUnit::of_char('\n'), offset - node.range().start() + TextUnit::of_char('\n'),
TextUnit::of_str(node_text), TextUnit::of_str(node_text),
@ -79,3 +98,15 @@ fn remove_newline(
" ".to_string(), " ".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 "",
_ => (),
}
" "
}

View file

@ -195,7 +195,7 @@ fn foo() {
} }
", r" ", r"
fn foo() { fn foo() {
<|>foo(1, ) <|>foo(1)
} }
"); ");
} }
@ -221,7 +221,7 @@ fn foo() {
} }
", r" ", r"
fn foo() { fn foo() {
foo(1, 2, 3, ) foo(1, 2, 3)
} }
"); ");
} }