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 // When using the Vim plugin:
44 // "command": "rust-analyzer.onEnter",
45 // "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust && vim.mode == 'Insert'"
49 // image::https://user-images.githubusercontent.com/48062697/113065578-04c21800-91b1-11eb-82b8-22b8c481e645.gif[]
50 pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<TextEdit> {
51 let parse = db.parse(position.file_id);
52 let file = parse.tree();
53 let token = file.syntax().token_at_offset(position.offset).left_biased()?;
55 if let Some(comment) = ast::Comment::cast(token.clone()) {
56 return on_enter_in_comment(&comment, &file, position.offset);
59 if token.kind() == L_CURLY {
60 // Typing enter after the `{` of a block expression, where the `}` is on the same line
61 if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
62 .and_then(|block| on_enter_in_block(block, position))
64 cov_mark::hit!(indent_block_contents);
68 // Typing enter after the `{` of a use tree list.
69 if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
70 .and_then(|list| on_enter_in_use_tree_list(list, position))
72 cov_mark::hit!(indent_block_contents);
80 fn on_enter_in_comment(
81 comment: &ast::Comment,
82 file: &ast::SourceFile,
84 ) -> Option<TextEdit> {
85 if comment.kind().shape.is_block() {
89 let prefix = comment.prefix();
90 let comment_range = comment.syntax().text_range();
91 if offset < comment_range.start() + TextSize::of(prefix) {
95 let mut remove_trailing_whitespace = false;
96 // Continuing single-line non-doc comments (like this one :) ) is annoying
97 if prefix == "//" && comment_range.end() == offset {
98 if comment.text().ends_with(' ') {
99 cov_mark::hit!(continues_end_of_line_comment_with_space);
100 remove_trailing_whitespace = true;
101 } else if !followed_by_comment(comment) {
106 let indent = node_indent(file, comment.syntax())?;
107 let inserted = format!("\n{}{} $0", indent, prefix);
108 let delete = if remove_trailing_whitespace {
109 let trimmed_len = comment.text().trim_end().len() as u32;
110 let trailing_whitespace_len = comment.text().len() as u32 - trimmed_len;
111 TextRange::new(offset - TextSize::from(trailing_whitespace_len), offset)
113 TextRange::empty(offset)
115 let edit = TextEdit::replace(delete, inserted);
119 fn on_enter_in_block(block: ast::BlockExpr, position: FilePosition) -> Option<TextEdit> {
120 let contents = block_contents(&block)?;
122 if block.syntax().text().contains_char('\n') {
126 let indent = IndentLevel::from_node(block.syntax());
127 let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
128 edit.union(TextEdit::insert(contents.text_range().end(), format!("\n{}", indent))).ok()?;
132 fn on_enter_in_use_tree_list(list: ast::UseTreeList, position: FilePosition) -> Option<TextEdit> {
133 if list.syntax().text().contains_char('\n') {
137 let indent = IndentLevel::from_node(list.syntax());
138 let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
139 edit.union(TextEdit::insert(
140 list.r_curly_token()?.text_range().start(),
141 format!("\n{}", indent),
147 fn block_contents(block: &ast::BlockExpr) -> Option<SyntaxNode> {
148 let mut node = block.tail_expr().map(|e| e.syntax().clone());
150 for stmt in block.statements() {
152 // More than 1 node in the block
156 node = Some(stmt.syntax().clone());
162 fn followed_by_comment(comment: &ast::Comment) -> bool {
163 let ws = match comment.syntax().next_token().and_then(ast::Whitespace::cast) {
165 None => return false,
167 if ws.spans_multiple_lines() {
170 ws.syntax().next_token().and_then(ast::Comment::cast).is_some()
173 fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
174 let ws = match file.syntax().token_at_offset(token.text_range().start()) {
175 TokenAtOffset::Between(l, r) => {
176 assert!(r == *token);
179 TokenAtOffset::Single(n) => {
180 assert!(n == *token);
181 return Some("".into());
183 TokenAtOffset::None => unreachable!(),
185 if ws.kind() != WHITESPACE {
188 let text = ws.text();
189 let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
190 Some(text[pos..].into())
195 use stdx::trim_indent;
196 use test_utils::assert_eq_text;
200 fn apply_on_enter(before: &str) -> Option<String> {
201 let (analysis, position) = fixture::position(before);
202 let result = analysis.on_enter(position).unwrap()?;
204 let mut actual = analysis.file_text(position.file_id).unwrap().to_string();
205 result.apply(&mut actual);
209 fn do_check(ra_fixture_before: &str, ra_fixture_after: &str) {
210 let ra_fixture_after = &trim_indent(ra_fixture_after);
211 let actual = apply_on_enter(ra_fixture_before).unwrap();
212 assert_eq_text!(ra_fixture_after, &actual);
215 fn do_check_noop(ra_fixture_text: &str) {
216 assert!(apply_on_enter(ra_fixture_text).is_none())
220 fn continues_doc_comment() {
267 fn does_not_continue_before_doc_comment() {
268 do_check_noop(r"$0//! docz");
272 fn continues_another_doc_comment() {
276 //! Documentation for$0 on enter
282 //! Documentation for
291 fn continues_code_comment_in_the_middle_of_line() {
310 fn continues_code_comment_in_the_middle_several_lines() {
331 fn does_not_continue_end_of_line_comment() {
343 fn continues_end_of_line_comment_with_space() {
344 cov_mark::check!(continues_end_of_line_comment_with_space);
363 fn trims_all_trailing_whitespace() {
382 fn indents_fn_body_block() {
383 cov_mark::check!(indent_block_contents);
397 fn indents_block_expr() {
415 fn indents_match_arm() {
439 fn indents_block_with_statement() {
463 fn indents_nested_blocks() {
477 fn does_not_indent_empty_block() {
491 fn does_not_indent_block_with_too_much_content() {
494 fn f() {$0 a = b; ()}
499 fn f() {$0 a = b; a = b; }
505 fn does_not_indent_multiline_block() {
522 fn indents_use_tree_list() {
535 use crate::{$0Object, path::to::OtherThing};
539 $0Object, path::to::OtherThing
545 use {crate::{$0Object, path::to::OtherThing}};
549 $0Object, path::to::OtherThing
556 crate::{$0Object, path::to::OtherThing}
562 $0Object, path::to::OtherThing
570 fn does_not_indent_use_tree_list_when_not_at_curly_brace() {
579 fn does_not_indent_use_tree_list_without_curly_braces() {
603 fn does_not_indent_multiline_use_tree_list() {