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);
62 fn on_enter_in_comment(
63 comment: &ast::Comment,
64 file: &ast::SourceFile,
66 ) -> Option<TextEdit> {
67 if comment.kind().shape.is_block() {
71 let prefix = comment.prefix();
72 let comment_range = comment.syntax().text_range();
73 if offset < comment_range.start() + TextSize::of(prefix) {
77 let mut remove_trailing_whitespace = false;
78 // Continuing single-line non-doc comments (like this one :) ) is annoying
79 if prefix == "//" && comment_range.end() == offset {
80 if comment.text().ends_with(' ') {
81 cov_mark::hit!(continues_end_of_line_comment_with_space);
82 remove_trailing_whitespace = true;
83 } else if !followed_by_comment(&comment) {
88 let indent = node_indent(&file, comment.syntax())?;
89 let inserted = format!("\n{}{} $0", indent, prefix);
90 let delete = if remove_trailing_whitespace {
91 let trimmed_len = comment.text().trim_end().len() as u32;
92 let trailing_whitespace_len = comment.text().len() as u32 - trimmed_len;
93 TextRange::new(offset - TextSize::from(trailing_whitespace_len), offset)
95 TextRange::empty(offset)
97 let edit = TextEdit::replace(delete, inserted);
101 fn on_enter_in_block(block: ast::BlockExpr, position: FilePosition) -> Option<TextEdit> {
102 let contents = block_contents(&block)?;
104 if block.syntax().text().contains_char('\n') {
108 let indent = IndentLevel::from_node(block.syntax());
109 let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
110 edit.union(TextEdit::insert(contents.text_range().end(), format!("\n{}", indent))).ok()?;
114 fn block_contents(block: &ast::BlockExpr) -> Option<SyntaxNode> {
115 let mut node = block.tail_expr().map(|e| e.syntax().clone());
117 for stmt in block.statements() {
119 // More than 1 node in the block
123 node = Some(stmt.syntax().clone());
129 fn followed_by_comment(comment: &ast::Comment) -> bool {
130 let ws = match comment.syntax().next_token().and_then(ast::Whitespace::cast) {
132 None => return false,
134 if ws.spans_multiple_lines() {
137 ws.syntax().next_token().and_then(ast::Comment::cast).is_some()
140 fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
141 let ws = match file.syntax().token_at_offset(token.text_range().start()) {
142 TokenAtOffset::Between(l, r) => {
143 assert!(r == *token);
146 TokenAtOffset::Single(n) => {
147 assert!(n == *token);
148 return Some("".into());
150 TokenAtOffset::None => unreachable!(),
152 if ws.kind() != WHITESPACE {
155 let text = ws.text();
156 let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
157 Some(text[pos..].into())
162 use stdx::trim_indent;
163 use test_utils::assert_eq_text;
167 fn apply_on_enter(before: &str) -> Option<String> {
168 let (analysis, position) = fixture::position(&before);
169 let result = analysis.on_enter(position).unwrap()?;
171 let mut actual = analysis.file_text(position.file_id).unwrap().to_string();
172 result.apply(&mut actual);
176 fn do_check(ra_fixture_before: &str, ra_fixture_after: &str) {
177 let ra_fixture_after = &trim_indent(ra_fixture_after);
178 let actual = apply_on_enter(ra_fixture_before).unwrap();
179 assert_eq_text!(ra_fixture_after, &actual);
182 fn do_check_noop(ra_fixture_text: &str) {
183 assert!(apply_on_enter(ra_fixture_text).is_none())
187 fn continues_doc_comment() {
234 fn does_not_continue_before_doc_comment() {
235 do_check_noop(r"$0//! docz");
239 fn continues_another_doc_comment() {
243 //! Documentation for$0 on enter
249 //! Documentation for
258 fn continues_code_comment_in_the_middle_of_line() {
277 fn continues_code_comment_in_the_middle_several_lines() {
298 fn does_not_continue_end_of_line_comment() {
310 fn continues_end_of_line_comment_with_space() {
311 cov_mark::check!(continues_end_of_line_comment_with_space);
330 fn trims_all_trailing_whitespace() {
349 fn indents_fn_body_block() {
350 cov_mark::check!(indent_block_contents);
364 fn indents_block_expr() {
382 fn indents_match_arm() {
406 fn indents_block_with_statement() {
430 fn indents_nested_blocks() {
444 fn does_not_indent_empty_block() {
458 fn does_not_indent_block_with_too_much_content() {
461 fn f() {$0 a = b; ()}
466 fn f() {$0 a = b; a = b; }
472 fn does_not_indent_multiline_block() {