aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide/src/typing/on_enter.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide/src/typing/on_enter.rs')
-rw-r--r--crates/ra_ide/src/typing/on_enter.rs216
1 files changed, 216 insertions, 0 deletions
diff --git a/crates/ra_ide/src/typing/on_enter.rs b/crates/ra_ide/src/typing/on_enter.rs
new file mode 100644
index 000000000..6bcf2d72b
--- /dev/null
+++ b/crates/ra_ide/src/typing/on_enter.rs
@@ -0,0 +1,216 @@
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.
3
4use ra_db::{FilePosition, SourceDatabase};
5use ra_ide_db::RootDatabase;
6use ra_syntax::{
7 ast::{self, AstToken},
8 AstNode, SmolStr, SourceFile,
9 SyntaxKind::*,
10 SyntaxToken, TextUnit, TokenAtOffset,
11};
12use ra_text_edit::TextEdit;
13
14use crate::{SourceChange, SourceFileEdit};
15
16pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
17 let parse = db.parse(position.file_id);
18 let file = parse.tree();
19 let comment = file
20 .syntax()
21 .token_at_offset(position.offset)
22 .left_biased()
23 .and_then(ast::Comment::cast)?;
24
25 if comment.kind().shape.is_block() {
26 return None;
27 }
28
29 let prefix = comment.prefix();
30 let comment_range = comment.syntax().text_range();
31 if position.offset < comment_range.start() + TextUnit::of_str(prefix) {
32 return None;
33 }
34
35 // Continuing single-line non-doc comments (like this one :) ) is annoying
36 if prefix == "//" && comment_range.end() == position.offset && !followed_by_comment(&comment) {
37 return None;
38 }
39
40 let indent = node_indent(&file, comment.syntax())?;
41 let inserted = format!("\n{}{} ", indent, prefix);
42 let cursor_position = position.offset + TextUnit::of_str(&inserted);
43 let edit = TextEdit::insert(position.offset, inserted);
44
45 Some(
46 SourceChange::source_file_edit(
47 "on enter",
48 SourceFileEdit { edit, file_id: position.file_id },
49 )
50 .with_cursor(FilePosition { offset: cursor_position, file_id: position.file_id }),
51 )
52}
53
54fn followed_by_comment(comment: &ast::Comment) -> bool {
55 let ws = match comment.syntax().next_token().and_then(ast::Whitespace::cast) {
56 Some(it) => it,
57 None => return false,
58 };
59 if ws.spans_multiple_lines() {
60 return false;
61 }
62 ws.syntax().next_token().and_then(ast::Comment::cast).is_some()
63}
64
65fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
66 let ws = match file.syntax().token_at_offset(token.text_range().start()) {
67 TokenAtOffset::Between(l, r) => {
68 assert!(r == *token);
69 l
70 }
71 TokenAtOffset::Single(n) => {
72 assert!(n == *token);
73 return Some("".into());
74 }
75 TokenAtOffset::None => unreachable!(),
76 };
77 if ws.kind() != WHITESPACE {
78 return None;
79 }
80 let text = ws.text();
81 let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
82 Some(text[pos..].into())
83}
84
85#[cfg(test)]
86mod tests {
87 use test_utils::{add_cursor, assert_eq_text, extract_offset};
88
89 use crate::mock_analysis::single_file;
90
91 use super::*;
92
93 fn apply_on_enter(before: &str) -> Option<String> {
94 let (offset, before) = extract_offset(before);
95 let (analysis, file_id) = single_file(&before);
96 let result = analysis.on_enter(FilePosition { offset, file_id }).unwrap()?;
97
98 assert_eq!(result.source_file_edits.len(), 1);
99 let actual = result.source_file_edits[0].edit.apply(&before);
100 let actual = add_cursor(&actual, result.cursor_position.unwrap().offset);
101 Some(actual)
102 }
103
104 fn do_check(ra_fixture_before: &str, ra_fixture_after: &str) {
105 let actual = apply_on_enter(ra_fixture_before).unwrap();
106 assert_eq_text!(ra_fixture_after, &actual);
107 }
108
109 fn do_check_noop(ra_fixture_text: &str) {
110 assert!(apply_on_enter(ra_fixture_text).is_none())
111 }
112
113 #[test]
114 fn continues_doc_comment() {
115 do_check(
116 r"
117/// Some docs<|>
118fn foo() {
119}
120",
121 r"
122/// Some docs
123/// <|>
124fn foo() {
125}
126",
127 );
128
129 do_check(
130 r"
131impl S {
132 /// Some<|> docs.
133 fn foo() {}
134}
135",
136 r"
137impl S {
138 /// Some
139 /// <|> docs.
140 fn foo() {}
141}
142",
143 );
144
145 do_check(
146 r"
147///<|> Some docs
148fn foo() {
149}
150",
151 r"
152///
153/// <|> Some docs
154fn foo() {
155}
156",
157 );
158 }
159
160 #[test]
161 fn does_not_continue_before_doc_comment() {
162 do_check_noop(r"<|>//! docz");
163 }
164
165 #[test]
166 fn continues_code_comment_in_the_middle_of_line() {
167 do_check(
168 r"
169fn main() {
170 // Fix<|> me
171 let x = 1 + 1;
172}
173",
174 r"
175fn main() {
176 // Fix
177 // <|> me
178 let x = 1 + 1;
179}
180",
181 );
182 }
183
184 #[test]
185 fn continues_code_comment_in_the_middle_several_lines() {
186 do_check(
187 r"
188fn main() {
189 // Fix<|>
190 // me
191 let x = 1 + 1;
192}
193",
194 r"
195fn main() {
196 // Fix
197 // <|>
198 // me
199 let x = 1 + 1;
200}
201",
202 );
203 }
204
205 #[test]
206 fn does_not_continue_end_of_code_comment() {
207 do_check_noop(
208 r"
209fn main() {
210 // Fix me<|>
211 let x = 1 + 1;
212}
213",
214 );
215 }
216}