1 use ide_assists::utils::extract_trivial_expression;
2 use ide_db::syntax_helpers::node_ext::expr_as_name_ref;
3 use itertools::Itertools;
5 ast::{self, AstNode, AstToken, IsString},
6 NodeOrToken, SourceFile, SyntaxElement,
7 SyntaxKind::{self, USE_TREE, WHITESPACE},
8 SyntaxToken, TextRange, TextSize, T,
11 use text_edit::{TextEdit, TextEditBuilder};
13 pub struct JoinLinesConfig {
14 pub join_else_if: bool,
15 pub remove_trailing_comma: bool,
16 pub unwrap_trivial_blocks: bool,
17 pub join_assignments: bool,
20 // Feature: Join Lines
22 // Join selected lines into one, smartly fixing up whitespace, trailing commas, and braces.
25 // https://user-images.githubusercontent.com/1711539/124515923-4504e800-dde9-11eb-8d58-d97945a1a785.gif[this gif]
26 // for the cases handled specially by joined lines.
29 // | Editor | Action Name
31 // | VS Code | **Rust Analyzer: Join lines**
34 // image::https://user-images.githubusercontent.com/48062697/113020661-b6922200-917a-11eb-87c4-b75acc028f11.gif[]
35 pub(crate) fn join_lines(
36 config: &JoinLinesConfig,
40 let range = if range.is_empty() {
41 let syntax = file.syntax();
42 let text = syntax.text().slice(range.start()..);
43 let pos = match text.find_char('\n') {
44 None => return TextEdit::builder().finish(),
47 TextRange::at(range.start() + pos, TextSize::of('\n'))
52 let mut edit = TextEdit::builder();
53 match file.syntax().covering_element(range) {
54 NodeOrToken::Node(node) => {
55 for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) {
56 remove_newlines(config, &mut edit, &token, range)
59 NodeOrToken::Token(token) => remove_newlines(config, &mut edit, &token, range),
65 config: &JoinLinesConfig,
66 edit: &mut TextEditBuilder,
70 let intersection = match range.intersect(token.text_range()) {
75 let range = intersection - token.text_range().start();
76 let text = token.text();
77 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
78 let pos: TextSize = (pos as u32).into();
79 let offset = token.text_range().start() + range.start() + pos;
80 if !edit.invalidates_offset(offset) {
81 remove_newline(config, edit, token, offset);
87 config: &JoinLinesConfig,
88 edit: &mut TextEditBuilder,
92 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 {
93 let n_spaces_after_line_break = {
94 let suff = &token.text()[TextRange::new(
95 offset - token.text_range().start() + TextSize::of('\n'),
96 TextSize::of(token.text()),
98 suff.bytes().take_while(|&b| b == b' ').count()
101 let mut no_space = false;
102 if let Some(string) = ast::String::cast(token.clone()) {
103 if let Some(range) = string.open_quote_text_range() {
104 cov_mark::hit!(join_string_literal_open_quote);
105 no_space |= range.end() == offset;
107 if let Some(range) = string.close_quote_text_range() {
108 cov_mark::hit!(join_string_literal_close_quote);
109 no_space |= range.start()
112 + TextSize::try_from(n_spaces_after_line_break).unwrap();
116 let range = TextRange::at(offset, ((n_spaces_after_line_break + 1) as u32).into());
117 let replace_with = if no_space { "" } else { " " };
118 edit.replace(range, replace_with.to_string());
122 // The node is between two other nodes
123 let (prev, next) = match (token.prev_sibling_or_token(), token.next_sibling_or_token()) {
124 (Some(prev), Some(next)) => (prev, next),
128 if config.remove_trailing_comma && prev.kind() == T![,] {
130 T![')'] | T![']'] => {
131 // Removes: trailing comma, newline (incl. surrounding whitespace)
132 edit.delete(TextRange::new(prev.text_range().start(), token.text_range().end()));
136 // Removes: comma, newline (incl. surrounding whitespace)
137 let space = match prev.prev_sibling_or_token() {
138 Some(left) => compute_ws(left.kind(), next.kind()),
142 TextRange::new(prev.text_range().start(), token.text_range().end()),
151 if config.join_else_if {
152 if let (Some(prev), Some(_next)) = (as_if_expr(&prev), as_if_expr(&next)) {
153 match prev.else_token() {
154 Some(_) => cov_mark::hit!(join_two_ifs_with_existing_else),
156 cov_mark::hit!(join_two_ifs);
157 edit.replace(token.text_range(), " else ".to_string());
164 if config.join_assignments {
165 if join_assignments(edit, &prev, &next).is_some() {
170 if config.unwrap_trivial_blocks {
171 // Special case that turns something like:
179 // into `my_function(<some-expr>)`
180 if join_single_expr_block(edit, token).is_some() {
190 if join_single_use_tree(edit, token).is_some() {
195 if let (Some(_), Some(next)) = (
196 prev.as_token().cloned().and_then(ast::Comment::cast),
197 next.as_token().cloned().and_then(ast::Comment::cast),
199 // Removes: newline (incl. surrounding whitespace), start of the next comment
200 edit.delete(TextRange::new(
201 token.text_range().start(),
202 next.syntax().text_range().start() + TextSize::of(next.prefix()),
207 // Remove newline but add a computed amount of whitespace characters
208 edit.replace(token.text_range(), compute_ws(prev.kind(), next.kind()).to_string());
211 fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
212 let block_expr = ast::BlockExpr::cast(token.ancestors().nth(1)?)?;
213 if !block_expr.is_standalone() {
216 let expr = extract_trivial_expression(&block_expr)?;
218 let block_range = block_expr.syntax().text_range();
219 let mut buf = expr.syntax().text().to_string();
221 // Match block needs to have a comma after the block
222 if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) {
223 if match_arm.comma_token().is_none() {
228 edit.replace(block_range, buf);
233 fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
234 let use_tree_list = ast::UseTreeList::cast(token.parent()?)?;
235 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
236 edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string());
241 edit: &mut TextEditBuilder,
242 prev: &SyntaxElement,
243 next: &SyntaxElement,
245 let let_stmt = ast::LetStmt::cast(prev.as_node()?.clone())?;
246 if let_stmt.eq_token().is_some() {
247 cov_mark::hit!(join_assignments_already_initialized);
250 let let_ident_pat = match let_stmt.pat()? {
251 ast::Pat::IdentPat(it) => it,
255 let expr_stmt = ast::ExprStmt::cast(next.as_node()?.clone())?;
256 let bin_expr = match expr_stmt.expr()? {
257 ast::Expr::BinExpr(it) => it,
260 if !matches!(bin_expr.op_kind()?, ast::BinaryOp::Assignment { op: None }) {
263 let lhs = bin_expr.lhs()?;
264 let name_ref = expr_as_name_ref(&lhs)?;
266 if name_ref.to_string() != let_ident_pat.syntax().to_string() {
267 cov_mark::hit!(join_assignments_mismatch);
271 edit.delete(let_stmt.semicolon_token()?.text_range().cover(lhs.syntax().text_range()));
275 fn as_if_expr(element: &SyntaxElement) -> Option<ast::IfExpr> {
276 let mut node = element.as_node()?.clone();
277 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
278 node = stmt.expr()?.syntax().clone();
280 ast::IfExpr::cast(node)
283 fn compute_ws(left: SyntaxKind, right: SyntaxKind) -> &'static str {
285 T!['('] | T!['['] => return "",
287 if let USE_TREE = right {
294 T![')'] | T![']'] => return "",
296 if let USE_TREE = left {
308 use syntax::SourceFile;
309 use test_utils::{add_cursor, assert_eq_text, extract_offset, extract_range};
313 fn check_join_lines(ra_fixture_before: &str, ra_fixture_after: &str) {
314 let config = JoinLinesConfig {
316 remove_trailing_comma: true,
317 unwrap_trivial_blocks: true,
318 join_assignments: true,
321 let (before_cursor_pos, before) = extract_offset(ra_fixture_before);
322 let file = SourceFile::parse(&before).ok().unwrap();
324 let range = TextRange::empty(before_cursor_pos);
325 let result = join_lines(&config, &file, range);
328 let mut actual = before;
329 result.apply(&mut actual);
332 let actual_cursor_pos = result
333 .apply_to_offset(before_cursor_pos)
334 .expect("cursor position is affected by the edit");
335 let actual = add_cursor(&actual, actual_cursor_pos);
336 assert_eq_text!(ra_fixture_after, &actual);
339 fn check_join_lines_sel(ra_fixture_before: &str, ra_fixture_after: &str) {
340 let config = JoinLinesConfig {
342 remove_trailing_comma: true,
343 unwrap_trivial_blocks: true,
344 join_assignments: true,
347 let (sel, before) = extract_range(ra_fixture_before);
348 let parse = SourceFile::parse(&before);
349 let result = join_lines(&config, &parse.tree(), sel);
351 let mut actual = before;
352 result.apply(&mut actual);
355 assert_eq_text!(ra_fixture_after, &actual);
359 fn test_join_lines_comma() {
376 fn test_join_lines_lambda_block() {
379 pub fn reparse(&self, edit: &AtomTextEdit) -> File {
380 $0self.incremental_reparse(edit).unwrap_or_else(|| {
381 self.full_reparse(edit)
386 pub fn reparse(&self, edit: &AtomTextEdit) -> File {
387 $0self.incremental_reparse(edit).unwrap_or_else(|| self.full_reparse(edit))
394 fn test_join_lines_block() {
410 fn test_join_lines_diverging_block() {
436 fn join_lines_adds_comma_for_block_in_match_arm() {
439 fn foo(e: Result<U, V>) {
448 fn foo(e: Result<U, V>) {
458 fn join_lines_multiline_in_block() {
475 $0 Some(ty) => match ty {
486 fn join_lines_keeps_comma_for_block_in_match_arm() {
487 // We already have a comma
490 fn foo(e: Result<U, V>) {
499 fn foo(e: Result<U, V>) {
507 // comma with whitespace between brace and ,
510 fn foo(e: Result<U, V>) {
519 fn foo(e: Result<U, V>) {
527 // comma with newline between brace and ,
530 fn foo(e: Result<U, V>) {
540 fn foo(e: Result<U, V>) {
551 fn join_lines_keeps_comma_with_single_arg_tuple() {
552 // A single arg tuple
566 // single arg tuple with whitespace between brace and comma
580 // single arg tuple with newline between brace and comma
598 fn test_join_lines_use_items_left() {
599 // No space after the '{'
606 $0use syntax::{TextSize, TextRange,
612 fn test_join_lines_use_items_right() {
613 // No space after the '}'
617 $0 TextSize, TextRange
621 $0 TextSize, TextRange};",
626 fn test_join_lines_use_items_right_comma() {
627 // No space after the '}'
631 $0 TextSize, TextRange,
635 $0 TextSize, TextRange};",
640 fn test_join_lines_use_tree() {
645 find_token_at_offset,
651 algo::$0find_token_at_offset,
658 fn test_join_lines_normal_comments() {
675 fn test_join_lines_doc_comments() {
692 fn test_join_lines_mod_comments() {
709 fn test_join_lines_multiline_comments_1() {
726 fn test_join_lines_multiline_comments_2() {
747 fn test_join_lines_selection_fn_args() {
748 check_join_lines_sel(
766 fn test_join_lines_selection_struct() {
767 check_join_lines_sel(
774 struct Foo { f: u32 }
780 fn test_join_lines_selection_dot_chain() {
781 check_join_lines_sel(
784 join($0type_params.type_params()
785 .filter_map(|it| it.name())
786 .map(|it| it.text())$0)
790 join(type_params.type_params().filter_map(|it| it.name()).map(|it| it.text()))
796 fn test_join_lines_selection_lambda_block_body() {
797 check_join_lines_sel(
799 pub fn handle_find_matching_brace() {
802 world.analysis().matching_brace(&file, offset).unwrap_or(offset)
807 pub fn handle_find_matching_brace() {
809 .map(|offset| world.analysis().matching_brace(&file, offset).unwrap_or(offset))
816 fn test_join_lines_commented_block() {
839 fn join_lines_mandatory_blocks_block() {
902 fn join_string_literal() {
904 cov_mark::check!(join_string_literal_open_quote);
923 cov_mark::check!(join_string_literal_close_quote);
972 fn join_last_line_empty() {
985 cov_mark::check!(join_two_ifs);
1010 fn join_two_ifs_with_existing_else() {
1011 cov_mark::check!(join_two_ifs_with_existing_else);
1040 fn join_assignments() {
1055 cov_mark::check!(join_assignments_mismatch);
1067 let qux;$0 foo = "bar";
1072 cov_mark::check!(join_assignments_already_initialized);
1082 let foo = "bar";$0 foo = "bar";