1 //! Handles the `Enter` key press. At the momently, this only continues
2 //! comments, but should handle indent some time in the future as well.
4 use ide_db::base_db::{FilePosition, SourceDatabase};
5 use ide_db::RootDatabase;
7 algo::find_node_at_offset,
8 ast::{self, edit::IndentLevel, AstToken},
9 AstNode, SmolStr, SourceFile,
11 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset,
14 use text_edit::TextEdit;
18 // rust-analyzer can override kbd:[Enter] key to make it smarter:
20 // - kbd:[Enter] inside triple-slash comments automatically inserts `///`
21 // - kbd:[Enter] in the middle or after a trailing space in `//` inserts `//`
22 // - kbd:[Enter] inside `//!` doc comments automatically inserts `//!`
23 // - kbd:[Enter] after `{` indents contents and closing `}` of single-line block
25 // This action needs to be assigned to shortcut explicitly.
29 // Add the following to `keybindings.json`:
34 // "command": "rust-analyzer.onEnter",
35 // "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust"
39 // image::https://user-images.githubusercontent.com/48062697/113065578-04c21800-91b1-11eb-82b8-22b8c481e645.gif[]
40 pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<TextEdit> {
41 let parse = db.parse(position.file_id);
42 let file = parse.tree();
43 let token = file.syntax().token_at_offset(position.offset).left_biased()?;
45 if let Some(comment) = ast::Comment::cast(token.clone()) {
46 return on_enter_in_comment(&comment, &file, position.offset);
49 if token.kind() == L_CURLY {
50 // Typing enter after the `{` of a block expression, where the `}` is on the same line
51 if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
52 .and_then(|block| on_enter_in_block(block, position))
54 cov_mark::hit!(indent_block_contents);
58 // Typing enter after the `{` of a use tree list.
59 if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
60 .and_then(|list| on_enter_in_use_tree_list(list, position))
62 cov_mark::hit!(indent_block_contents);
70 fn on_enter_in_comment(
71 comment: &ast::Comment,
72 file: &ast::SourceFile,
74 ) -> Option<TextEdit> {
75 if comment.kind().shape.is_block() {
79 let prefix = comment.prefix();
80 let comment_range = comment.syntax().text_range();
81 if offset < comment_range.start() + TextSize::of(prefix) {
85 let mut remove_trailing_whitespace = false;
86 // Continuing single-line non-doc comments (like this one :) ) is annoying
87 if prefix == "//" && comment_range.end() == offset {
88 if comment.text().ends_with(' ') {
89 cov_mark::hit!(continues_end_of_line_comment_with_space);
90 remove_trailing_whitespace = true;
91 } else if !followed_by_comment(&comment) {
96 let indent = node_indent(&file, comment.syntax())?;
97 let inserted = format!("\n{}{} $0", indent, prefix);
98 let delete = if remove_trailing_whitespace {
99 let trimmed_len = comment.text().trim_end().len() as u32;
100 let trailing_whitespace_len = comment.text().len() as u32 - trimmed_len;
101 TextRange::new(offset - TextSize::from(trailing_whitespace_len), offset)
103 TextRange::empty(offset)
105 let edit = TextEdit::replace(delete, inserted);
109 fn on_enter_in_block(block: ast::BlockExpr, position: FilePosition) -> Option<TextEdit> {
110 let contents = block_contents(&block)?;
112 if block.syntax().text().contains_char('\n') {
116 let indent = IndentLevel::from_node(block.syntax());
117 let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
118 edit.union(TextEdit::insert(contents.text_range().end(), format!("\n{}", indent))).ok()?;
122 fn on_enter_in_use_tree_list(list: ast::UseTreeList, position: FilePosition) -> Option<TextEdit> {
123 if list.syntax().text().contains_char('\n') {
127 let indent = IndentLevel::from_node(list.syntax());
128 let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
129 edit.union(TextEdit::insert(
130 list.r_curly_token()?.text_range().start(),
131 format!("\n{}", indent),
137 fn block_contents(block: &ast::BlockExpr) -> Option<SyntaxNode> {
138 let mut node = block.tail_expr().map(|e| e.syntax().clone());
140 for stmt in block.statements() {
142 // More than 1 node in the block
146 node = Some(stmt.syntax().clone());
152 fn followed_by_comment(comment: &ast::Comment) -> bool {
153 let ws = match comment.syntax().next_token().and_then(ast::Whitespace::cast) {
155 None => return false,
157 if ws.spans_multiple_lines() {
160 ws.syntax().next_token().and_then(ast::Comment::cast).is_some()
163 fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
164 let ws = match file.syntax().token_at_offset(token.text_range().start()) {
165 TokenAtOffset::Between(l, r) => {
166 assert!(r == *token);
169 TokenAtOffset::Single(n) => {
170 assert!(n == *token);
171 return Some("".into());
173 TokenAtOffset::None => unreachable!(),
175 if ws.kind() != WHITESPACE {
178 let text = ws.text();
179 let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
180 Some(text[pos..].into())
185 use stdx::trim_indent;
186 use test_utils::assert_eq_text;
190 fn apply_on_enter(before: &str) -> Option<String> {
191 let (analysis, position) = fixture::position(&before);
192 let result = analysis.on_enter(position).unwrap()?;
194 let mut actual = analysis.file_text(position.file_id).unwrap().to_string();
195 result.apply(&mut actual);
199 fn do_check(ra_fixture_before: &str, ra_fixture_after: &str) {
200 let ra_fixture_after = &trim_indent(ra_fixture_after);
201 let actual = apply_on_enter(ra_fixture_before).unwrap();
202 assert_eq_text!(ra_fixture_after, &actual);
205 fn do_check_noop(ra_fixture_text: &str) {
206 assert!(apply_on_enter(ra_fixture_text).is_none())
210 fn continues_doc_comment() {
257 fn does_not_continue_before_doc_comment() {
258 do_check_noop(r"$0//! docz");
262 fn continues_another_doc_comment() {
266 //! Documentation for$0 on enter
272 //! Documentation for
281 fn continues_code_comment_in_the_middle_of_line() {
300 fn continues_code_comment_in_the_middle_several_lines() {
321 fn does_not_continue_end_of_line_comment() {
333 fn continues_end_of_line_comment_with_space() {
334 cov_mark::check!(continues_end_of_line_comment_with_space);
353 fn trims_all_trailing_whitespace() {
372 fn indents_fn_body_block() {
373 cov_mark::check!(indent_block_contents);
387 fn indents_block_expr() {
405 fn indents_match_arm() {
429 fn indents_block_with_statement() {
453 fn indents_nested_blocks() {
467 fn does_not_indent_empty_block() {
481 fn does_not_indent_block_with_too_much_content() {
484 fn f() {$0 a = b; ()}
489 fn f() {$0 a = b; a = b; }
495 fn does_not_indent_multiline_block() {
512 fn indents_use_tree_list() {
525 use crate::{$0Object, path::to::OtherThing};
529 $0Object, path::to::OtherThing
535 use {crate::{$0Object, path::to::OtherThing}};
539 $0Object, path::to::OtherThing
546 crate::{$0Object, path::to::OtherThing}
552 $0Object, path::to::OtherThing
560 fn does_not_indent_use_tree_list_when_not_at_curly_brace() {
569 fn does_not_indent_use_tree_list_without_curly_braces() {
593 fn does_not_indent_multiline_use_tree_list() {