Skip to content

Commit 751562d

Browse files
committed
better introduce
1 parent bb64edf commit 751562d

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

crates/libeditor/src/code_actions.rs

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,17 +109,22 @@ pub fn introduce_variable<'a>(file: &'a File, range: TextRange) -> Option<impl F
109109
}
110110
Some(move || {
111111
let mut buf = String::new();
112+
let mut edit = EditBuilder::new();
113+
112114
buf.push_str("let var_name = ");
113115
expr.syntax().text().push_to(&mut buf);
114-
buf.push_str(";");
115-
indent.text().push_to(&mut buf);
116-
117-
let mut edit = EditBuilder::new();
118-
edit.replace(expr.syntax().range(), "var_name".to_string());
119-
edit.insert(anchor_stmt.syntax().range().start(), buf);
116+
if expr.syntax().range().start() == anchor_stmt.syntax().range().start() {
117+
edit.replace(expr.syntax().range(), buf);
118+
} else {
119+
buf.push_str(";");
120+
indent.text().push_to(&mut buf);
121+
edit.replace(expr.syntax().range(), "var_name".to_string());
122+
edit.insert(anchor_stmt.syntax().range().start(), buf);
123+
}
124+
let cursor_position = anchor_stmt.syntax().range().start() + TextUnit::of_str("let ");
120125
LocalEdit {
121126
edit: edit.finish(),
122-
cursor_position: Some(anchor_stmt.syntax().range().start() + TextUnit::of_str("let ")),
127+
cursor_position: Some(cursor_position),
123128
}
124129
})
125130
}
@@ -183,7 +188,7 @@ mod tests {
183188
}
184189

185190
#[test]
186-
fn test_intrdoduce_var() {
191+
fn test_intrdoduce_var_simple() {
187192
check_action_range(
188193
"
189194
fn foo() {
@@ -192,6 +197,19 @@ fn foo() {
192197
fn foo() {
193198
let <|>var_name = 1 + 1;
194199
foo(var_name);
200+
}",
201+
|file, range| introduce_variable(file, range).map(|f| f()),
202+
);
203+
}
204+
#[test]
205+
fn test_intrdoduce_var_expr_stmt() {
206+
check_action_range(
207+
"
208+
fn foo() {
209+
<|>1 + 1<|>;
210+
}", "
211+
fn foo() {
212+
let <|>var_name = 1 + 1;
195213
}",
196214
|file, range| introduce_variable(file, range).map(|f| f()),
197215
);

0 commit comments

Comments
 (0)