1 use std::convert::TryFrom;
3 use ide_assists::utils::extract_trivial_expression;
4 use itertools::Itertools;
6 algo::non_trivia_sibling,
7 ast::{self, AstNode, AstToken, IsString},
8 Direction, NodeOrToken, SourceFile,
9 SyntaxKind::{self, USE_TREE, WHITESPACE},
10 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
13 use text_edit::{TextEdit, TextEditBuilder};
15 // Feature: Join Lines
17 // Join selected lines into one, smartly fixing up whitespace, trailing commas, and braces.
20 // | Editor | Action Name
22 // | VS Code | **Rust Analyzer: Join lines**
25 // image::https://user-images.githubusercontent.com/48062697/113020661-b6922200-917a-11eb-87c4-b75acc028f11.gif[]
26 pub(crate) fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
27 let range = if range.is_empty() {
28 let syntax = file.syntax();
29 let text = syntax.text().slice(range.start()..);
30 let pos = match text.find_char('\n') {
31 None => return TextEdit::builder().finish(),
34 TextRange::at(range.start() + pos, TextSize::of('\n'))
39 let mut edit = TextEdit::builder();
40 match file.syntax().covering_element(range) {
41 NodeOrToken::Node(node) => {
42 for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) {
43 remove_newlines(&mut edit, &token, range)
46 NodeOrToken::Token(token) => remove_newlines(&mut edit, &token, range),
51 fn remove_newlines(edit: &mut TextEditBuilder, token: &SyntaxToken, range: TextRange) {
52 let intersection = match range.intersect(token.text_range()) {
57 let range = intersection - token.text_range().start();
58 let text = token.text();
59 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
60 let pos: TextSize = (pos as u32).into();
61 let offset = token.text_range().start() + range.start() + pos;
62 if !edit.invalidates_offset(offset) {
63 remove_newline(edit, &token, offset);
68 fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextSize) {
69 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 {
70 let n_spaces_after_line_break = {
71 let suff = &token.text()[TextRange::new(
72 offset - token.text_range().start() + TextSize::of('\n'),
73 TextSize::of(token.text()),
75 suff.bytes().take_while(|&b| b == b' ').count()
78 let mut no_space = false;
79 if let Some(string) = ast::String::cast(token.clone()) {
80 if let Some(range) = string.open_quote_text_range() {
81 cov_mark::hit!(join_string_literal_open_quote);
82 no_space |= range.end() == offset;
84 if let Some(range) = string.close_quote_text_range() {
85 cov_mark::hit!(join_string_literal_close_quote);
86 no_space |= range.start()
89 + TextSize::try_from(n_spaces_after_line_break).unwrap();
93 let range = TextRange::at(offset, ((n_spaces_after_line_break + 1) as u32).into());
94 let replace_with = if no_space { "" } else { " " };
95 edit.replace(range, replace_with.to_string());
99 // The node is between two other nodes
100 let (prev, next) = match (token.prev_sibling_or_token(), token.next_sibling_or_token()) {
101 (Some(prev), Some(next)) => (prev, next),
105 if is_trailing_comma(prev.kind(), next.kind()) {
106 // Removes: trailing comma, newline (incl. surrounding whitespace)
107 edit.delete(TextRange::new(prev.text_range().start(), token.text_range().end()));
110 if prev.kind() == T![,] && next.kind() == T!['}'] {
111 // Removes: comma, newline (incl. surrounding whitespace)
112 let space = if let Some(left) = prev.prev_sibling_or_token() {
113 compute_ws(left.kind(), next.kind())
118 TextRange::new(prev.text_range().start(), token.text_range().end()),
124 if let (Some(_), Some(next)) = (
125 prev.as_token().cloned().and_then(ast::Comment::cast),
126 next.as_token().cloned().and_then(ast::Comment::cast),
128 // Removes: newline (incl. surrounding whitespace), start of the next comment
129 edit.delete(TextRange::new(
130 token.text_range().start(),
131 next.syntax().text_range().start() + TextSize::of(next.prefix()),
136 // Special case that turns something like:
144 // into `my_function(<some-expr>)`
145 if join_single_expr_block(edit, token).is_some() {
155 if join_single_use_tree(edit, token).is_some() {
159 // Remove newline but add a computed amount of whitespace characters
160 edit.replace(token.text_range(), compute_ws(prev.kind(), next.kind()).to_string());
163 fn has_comma_after(node: &SyntaxNode) -> bool {
164 match non_trivia_sibling(node.clone().into(), Direction::Next) {
165 Some(n) => n.kind() == T![,],
170 fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
171 let block_expr = ast::BlockExpr::cast(token.parent()?)?;
172 if !block_expr.is_standalone() {
175 let expr = extract_trivial_expression(&block_expr)?;
177 let block_range = block_expr.syntax().text_range();
178 let mut buf = expr.syntax().text().to_string();
180 // Match block needs to have a comma after the block
181 if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) {
182 if !has_comma_after(match_arm.syntax()) {
187 edit.replace(block_range, buf);
192 fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
193 let use_tree_list = ast::UseTreeList::cast(token.parent()?)?;
194 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
195 edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string());
199 fn is_trailing_comma(left: SyntaxKind, right: SyntaxKind) -> bool {
200 matches!((left, right), (T![,], T![')']) | (T![,], T![']']))
203 fn compute_ws(left: SyntaxKind, right: SyntaxKind) -> &'static str {
205 T!['('] | T!['['] => return "",
207 if let USE_TREE = right {
214 T![')'] | T![']'] => return "",
216 if let USE_TREE = left {
228 use syntax::SourceFile;
229 use test_utils::{add_cursor, assert_eq_text, extract_offset, extract_range};
233 fn check_join_lines(ra_fixture_before: &str, ra_fixture_after: &str) {
234 let (before_cursor_pos, before) = extract_offset(ra_fixture_before);
235 let file = SourceFile::parse(&before).ok().unwrap();
237 let range = TextRange::empty(before_cursor_pos);
238 let result = join_lines(&file, range);
241 let mut actual = before;
242 result.apply(&mut actual);
245 let actual_cursor_pos = result
246 .apply_to_offset(before_cursor_pos)
247 .expect("cursor position is affected by the edit");
248 let actual = add_cursor(&actual, actual_cursor_pos);
249 assert_eq_text!(ra_fixture_after, &actual);
253 fn test_join_lines_comma() {
270 fn test_join_lines_lambda_block() {
273 pub fn reparse(&self, edit: &AtomTextEdit) -> File {
274 $0self.incremental_reparse(edit).unwrap_or_else(|| {
275 self.full_reparse(edit)
280 pub fn reparse(&self, edit: &AtomTextEdit) -> File {
281 $0self.incremental_reparse(edit).unwrap_or_else(|| self.full_reparse(edit))
288 fn test_join_lines_block() {
304 fn test_join_lines_diverging_block() {
330 fn join_lines_adds_comma_for_block_in_match_arm() {
333 fn foo(e: Result<U, V>) {
342 fn foo(e: Result<U, V>) {
352 fn join_lines_multiline_in_block() {
369 $0 Some(ty) => match ty {
380 fn join_lines_keeps_comma_for_block_in_match_arm() {
381 // We already have a comma
384 fn foo(e: Result<U, V>) {
393 fn foo(e: Result<U, V>) {
401 // comma with whitespace between brace and ,
404 fn foo(e: Result<U, V>) {
413 fn foo(e: Result<U, V>) {
421 // comma with newline between brace and ,
424 fn foo(e: Result<U, V>) {
434 fn foo(e: Result<U, V>) {
445 fn join_lines_keeps_comma_with_single_arg_tuple() {
446 // A single arg tuple
460 // single arg tuple with whitespace between brace and comma
474 // single arg tuple with newline between brace and comma
492 fn test_join_lines_use_items_left() {
493 // No space after the '{'
500 $0use syntax::{TextSize, TextRange,
506 fn test_join_lines_use_items_right() {
507 // No space after the '}'
511 $0 TextSize, TextRange
515 $0 TextSize, TextRange};",
520 fn test_join_lines_use_items_right_comma() {
521 // No space after the '}'
525 $0 TextSize, TextRange,
529 $0 TextSize, TextRange};",
534 fn test_join_lines_use_tree() {
539 find_token_at_offset,
545 algo::$0find_token_at_offset,
552 fn test_join_lines_normal_comments() {
569 fn test_join_lines_doc_comments() {
586 fn test_join_lines_mod_comments() {
603 fn test_join_lines_multiline_comments_1() {
620 fn test_join_lines_multiline_comments_2() {
640 fn check_join_lines_sel(ra_fixture_before: &str, ra_fixture_after: &str) {
641 let (sel, before) = extract_range(ra_fixture_before);
642 let parse = SourceFile::parse(&before);
643 let result = join_lines(&parse.tree(), sel);
645 let mut actual = before;
646 result.apply(&mut actual);
649 assert_eq_text!(ra_fixture_after, &actual);
653 fn test_join_lines_selection_fn_args() {
654 check_join_lines_sel(
672 fn test_join_lines_selection_struct() {
673 check_join_lines_sel(
680 struct Foo { f: u32 }
686 fn test_join_lines_selection_dot_chain() {
687 check_join_lines_sel(
690 join($0type_params.type_params()
691 .filter_map(|it| it.name())
692 .map(|it| it.text())$0)
696 join(type_params.type_params().filter_map(|it| it.name()).map(|it| it.text()))
702 fn test_join_lines_selection_lambda_block_body() {
703 check_join_lines_sel(
705 pub fn handle_find_matching_brace() {
708 world.analysis().matching_brace(&file, offset).unwrap_or(offset)
713 pub fn handle_find_matching_brace() {
715 .map(|offset| world.analysis().matching_brace(&file, offset).unwrap_or(offset))
722 fn test_join_lines_commented_block() {
745 fn join_lines_mandatory_blocks_block() {
808 fn join_string_literal() {
810 cov_mark::check!(join_string_literal_open_quote);
829 cov_mark::check!(join_string_literal_close_quote);
877 fn join_last_line_empty() {