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;
8 AstNode, SmolStr, SourceFile,
10 SyntaxToken, TextRange, TextSize, TokenAtOffset,
13 use text_edit::TextEdit;
17 // rust-analyzer can override kbd:[Enter] key to make it smarter:
19 // - kbd:[Enter] inside triple-slash comments automatically inserts `///`
20 // - kbd:[Enter] in the middle or after a trailing space in `//` inserts `//`
21 // - kbd:[Enter] inside `//!` doc comments automatically inserts `//!`
23 // This action needs to be assigned to shortcut explicitly.
27 // Add the following to `keybindings.json`:
32 // "command": "rust-analyzer.onEnter",
33 // "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust"
37 // image::https://user-images.githubusercontent.com/48062697/113065578-04c21800-91b1-11eb-82b8-22b8c481e645.gif[]
38 pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<TextEdit> {
39 let parse = db.parse(position.file_id);
40 let file = parse.tree();
43 .token_at_offset(position.offset)
45 .and_then(ast::Comment::cast)?;
47 if comment.kind().shape.is_block() {
51 let prefix = comment.prefix();
52 let comment_range = comment.syntax().text_range();
53 if position.offset < comment_range.start() + TextSize::of(prefix) {
57 let mut remove_trailing_whitespace = false;
58 // Continuing single-line non-doc comments (like this one :) ) is annoying
59 if prefix == "//" && comment_range.end() == position.offset {
60 if comment.text().ends_with(' ') {
61 cov_mark::hit!(continues_end_of_line_comment_with_space);
62 remove_trailing_whitespace = true;
63 } else if !followed_by_comment(&comment) {
68 let indent = node_indent(&file, comment.syntax())?;
69 let inserted = format!("\n{}{} $0", indent, prefix);
70 let delete = if remove_trailing_whitespace {
71 let trimmed_len = comment.text().trim_end().len() as u32;
72 let trailing_whitespace_len = comment.text().len() as u32 - trimmed_len;
73 TextRange::new(position.offset - TextSize::from(trailing_whitespace_len), position.offset)
75 TextRange::empty(position.offset)
77 let edit = TextEdit::replace(delete, inserted);
81 fn followed_by_comment(comment: &ast::Comment) -> bool {
82 let ws = match comment.syntax().next_token().and_then(ast::Whitespace::cast) {
86 if ws.spans_multiple_lines() {
89 ws.syntax().next_token().and_then(ast::Comment::cast).is_some()
92 fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
93 let ws = match file.syntax().token_at_offset(token.text_range().start()) {
94 TokenAtOffset::Between(l, r) => {
98 TokenAtOffset::Single(n) => {
100 return Some("".into());
102 TokenAtOffset::None => unreachable!(),
104 if ws.kind() != WHITESPACE {
107 let text = ws.text();
108 let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
109 Some(text[pos..].into())
114 use stdx::trim_indent;
115 use test_utils::assert_eq_text;
119 fn apply_on_enter(before: &str) -> Option<String> {
120 let (analysis, position) = fixture::position(&before);
121 let result = analysis.on_enter(position).unwrap()?;
123 let mut actual = analysis.file_text(position.file_id).unwrap().to_string();
124 result.apply(&mut actual);
128 fn do_check(ra_fixture_before: &str, ra_fixture_after: &str) {
129 let ra_fixture_after = &trim_indent(ra_fixture_after);
130 let actual = apply_on_enter(ra_fixture_before).unwrap();
131 assert_eq_text!(ra_fixture_after, &actual);
134 fn do_check_noop(ra_fixture_text: &str) {
135 assert!(apply_on_enter(ra_fixture_text).is_none())
139 fn continues_doc_comment() {
186 fn does_not_continue_before_doc_comment() {
187 do_check_noop(r"$0//! docz");
191 fn continues_another_doc_comment() {
195 //! Documentation for$0 on enter
201 //! Documentation for
210 fn continues_code_comment_in_the_middle_of_line() {
229 fn continues_code_comment_in_the_middle_several_lines() {
250 fn does_not_continue_end_of_line_comment() {
262 fn continues_end_of_line_comment_with_space() {
263 cov_mark::check!(continues_end_of_line_comment_with_space);
282 fn trims_all_trailing_whitespace() {