1 use assists::utils::extract_trivial_expression;
2 use itertools::Itertools;
4 algo::{find_covering_element, non_trivia_sibling},
5 ast::{self, AstNode, AstToken},
6 Direction, NodeOrToken, SourceFile,
7 SyntaxKind::{self, USE_TREE, WHITESPACE},
8 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
10 use text_edit::{TextEdit, TextEditBuilder};
12 // Feature: Join Lines
14 // Join selected lines into one, smartly fixing up whitespace, trailing commas, and braces.
17 // | Editor | Action Name
19 // | VS Code | **Rust Analyzer: Join lines**
21 pub(crate) fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
22 let range = if range.is_empty() {
23 let syntax = file.syntax();
24 let text = syntax.text().slice(range.start()..);
25 let pos = match text.find_char('\n') {
26 None => return TextEdit::builder().finish(),
29 TextRange::at(range.start() + pos, TextSize::of('\n'))
34 let node = match find_covering_element(file.syntax(), range) {
35 NodeOrToken::Node(node) => node,
36 NodeOrToken::Token(token) => token.parent(),
38 let mut edit = TextEdit::builder();
39 for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) {
40 let range = match range.intersect(token.text_range()) {
43 } - token.text_range().start();
44 let text = token.text();
45 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
46 let pos: TextSize = (pos as u32).into();
47 let off = token.text_range().start() + range.start() + pos;
48 if !edit.invalidates_offset(off) {
49 remove_newline(&mut edit, &token, off);
57 fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextSize) {
58 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 {
59 // The node is either the first or the last in the file
60 let suff = &token.text()[TextRange::new(
61 offset - token.text_range().start() + TextSize::of('\n'),
62 TextSize::of(token.text().as_str()),
64 let spaces = suff.bytes().take_while(|&b| b == b' ').count();
66 edit.replace(TextRange::at(offset, ((spaces + 1) as u32).into()), " ".to_string());
70 // The node is between two other nodes
71 let prev = token.prev_sibling_or_token().unwrap();
72 let next = token.next_sibling_or_token().unwrap();
73 if is_trailing_comma(prev.kind(), next.kind()) {
74 // Removes: trailing comma, newline (incl. surrounding whitespace)
75 edit.delete(TextRange::new(prev.text_range().start(), token.text_range().end()));
78 if prev.kind() == T![,] && next.kind() == T!['}'] {
79 // Removes: comma, newline (incl. surrounding whitespace)
80 let space = if let Some(left) = prev.prev_sibling_or_token() {
81 compute_ws(left.kind(), next.kind())
86 TextRange::new(prev.text_range().start(), token.text_range().end()),
92 if let (Some(_), Some(next)) = (
93 prev.as_token().cloned().and_then(ast::Comment::cast),
94 next.as_token().cloned().and_then(ast::Comment::cast),
96 // Removes: newline (incl. surrounding whitespace), start of the next comment
97 edit.delete(TextRange::new(
98 token.text_range().start(),
99 next.syntax().text_range().start() + TextSize::of(next.prefix()),
104 // Special case that turns something like:
112 // into `my_function(<some-expr>)`
113 if join_single_expr_block(edit, token).is_some() {
123 if join_single_use_tree(edit, token).is_some() {
127 // Remove newline but add a computed amount of whitespace characters
128 edit.replace(token.text_range(), compute_ws(prev.kind(), next.kind()).to_string());
131 fn has_comma_after(node: &SyntaxNode) -> bool {
132 match non_trivia_sibling(node.clone().into(), Direction::Next) {
133 Some(n) => n.kind() == T![,],
138 fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
139 let block_expr = ast::BlockExpr::cast(token.parent())?;
140 if !block_expr.is_standalone() {
143 let expr = extract_trivial_expression(&block_expr)?;
145 let block_range = block_expr.syntax().text_range();
146 let mut buf = expr.syntax().text().to_string();
148 // Match block needs to have a comma after the block
149 if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) {
150 if !has_comma_after(match_arm.syntax()) {
155 edit.replace(block_range, buf);
160 fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
161 let use_tree_list = ast::UseTreeList::cast(token.parent())?;
162 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
163 edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string());
167 fn is_trailing_comma(left: SyntaxKind, right: SyntaxKind) -> bool {
168 matches!((left, right), (T![,], T![')']) | (T![,], T![']']))
171 fn compute_ws(left: SyntaxKind, right: SyntaxKind) -> &'static str {
173 T!['('] | T!['['] => return "",
175 if let USE_TREE = right {
182 T![')'] | T![']'] => return "",
184 if let USE_TREE = left {
196 use syntax::SourceFile;
197 use test_utils::{add_cursor, assert_eq_text, extract_offset, extract_range};
201 fn check_join_lines(before: &str, after: &str) {
202 let (before_cursor_pos, before) = extract_offset(before);
203 let file = SourceFile::parse(&before).ok().unwrap();
205 let range = TextRange::empty(before_cursor_pos);
206 let result = join_lines(&file, range);
209 let mut actual = before.to_string();
210 result.apply(&mut actual);
213 let actual_cursor_pos = result
214 .apply_to_offset(before_cursor_pos)
215 .expect("cursor position is affected by the edit");
216 let actual = add_cursor(&actual, actual_cursor_pos);
217 assert_eq_text!(after, &actual);
221 fn test_join_lines_comma() {
238 fn test_join_lines_lambda_block() {
241 pub fn reparse(&self, edit: &AtomTextEdit) -> File {
242 $0self.incremental_reparse(edit).unwrap_or_else(|| {
243 self.full_reparse(edit)
248 pub fn reparse(&self, edit: &AtomTextEdit) -> File {
249 $0self.incremental_reparse(edit).unwrap_or_else(|| self.full_reparse(edit))
256 fn test_join_lines_block() {
272 fn test_join_lines_diverging_block() {
293 check_join_lines(before, after);
297 fn join_lines_adds_comma_for_block_in_match_arm() {
300 fn foo(e: Result<U, V>) {
309 fn foo(e: Result<U, V>) {
319 fn join_lines_multiline_in_block() {
336 $0 Some(ty) => match ty {
347 fn join_lines_keeps_comma_for_block_in_match_arm() {
348 // We already have a comma
351 fn foo(e: Result<U, V>) {
360 fn foo(e: Result<U, V>) {
368 // comma with whitespace between brace and ,
371 fn foo(e: Result<U, V>) {
380 fn foo(e: Result<U, V>) {
388 // comma with newline between brace and ,
391 fn foo(e: Result<U, V>) {
401 fn foo(e: Result<U, V>) {
412 fn join_lines_keeps_comma_with_single_arg_tuple() {
413 // A single arg tuple
427 // single arg tuple with whitespace between brace and comma
441 // single arg tuple with newline between brace and comma
459 fn test_join_lines_use_items_left() {
460 // No space after the '{'
467 $0use syntax::{TextSize, TextRange,
473 fn test_join_lines_use_items_right() {
474 // No space after the '}'
478 $0 TextSize, TextRange
482 $0 TextSize, TextRange};",
487 fn test_join_lines_use_items_right_comma() {
488 // No space after the '}'
492 $0 TextSize, TextRange,
496 $0 TextSize, TextRange};",
501 fn test_join_lines_use_tree() {
506 find_token_at_offset,
512 algo::$0find_token_at_offset,
519 fn test_join_lines_normal_comments() {
536 fn test_join_lines_doc_comments() {
553 fn test_join_lines_mod_comments() {
570 fn test_join_lines_multiline_comments_1() {
587 fn test_join_lines_multiline_comments_2() {
607 fn check_join_lines_sel(before: &str, after: &str) {
608 let (sel, before) = extract_range(before);
609 let parse = SourceFile::parse(&before);
610 let result = join_lines(&parse.tree(), sel);
612 let mut actual = before.to_string();
613 result.apply(&mut actual);
616 assert_eq_text!(after, &actual);
620 fn test_join_lines_selection_fn_args() {
621 check_join_lines_sel(
639 fn test_join_lines_selection_struct() {
640 check_join_lines_sel(
647 struct Foo { f: u32 }
653 fn test_join_lines_selection_dot_chain() {
654 check_join_lines_sel(
657 join($0type_params.type_params()
658 .filter_map(|it| it.name())
659 .map(|it| it.text())$0)
663 join(type_params.type_params().filter_map(|it| it.name()).map(|it| it.text()))
669 fn test_join_lines_selection_lambda_block_body() {
670 check_join_lines_sel(
672 pub fn handle_find_matching_brace() {
675 world.analysis().matching_brace(&file, offset).unwrap_or(offset)
680 pub fn handle_find_matching_brace() {
682 .map(|offset| world.analysis().matching_brace(&file, offset).unwrap_or(offset))
689 fn test_join_lines_commented_block() {
712 fn join_lines_mandatory_blocks_block() {