better introduce

This commit is contained in:
Aleksey Kladov 2018-09-06 01:19:24 +03:00
parent bb64edf8ba
commit 751562d2f7

View file

@ -109,17 +109,22 @@ pub fn introduce_variable<'a>(file: &'a File, range: TextRange) -> Option<impl F
} }
Some(move || { Some(move || {
let mut buf = String::new(); let mut buf = String::new();
let mut edit = EditBuilder::new();
buf.push_str("let var_name = "); buf.push_str("let var_name = ");
expr.syntax().text().push_to(&mut buf); expr.syntax().text().push_to(&mut buf);
buf.push_str(";"); if expr.syntax().range().start() == anchor_stmt.syntax().range().start() {
indent.text().push_to(&mut buf); edit.replace(expr.syntax().range(), buf);
} else {
let mut edit = EditBuilder::new(); buf.push_str(";");
edit.replace(expr.syntax().range(), "var_name".to_string()); indent.text().push_to(&mut buf);
edit.insert(anchor_stmt.syntax().range().start(), buf); edit.replace(expr.syntax().range(), "var_name".to_string());
edit.insert(anchor_stmt.syntax().range().start(), buf);
}
let cursor_position = anchor_stmt.syntax().range().start() + TextUnit::of_str("let ");
LocalEdit { LocalEdit {
edit: edit.finish(), edit: edit.finish(),
cursor_position: Some(anchor_stmt.syntax().range().start() + TextUnit::of_str("let ")), cursor_position: Some(cursor_position),
} }
}) })
} }
@ -183,7 +188,7 @@ mod tests {
} }
#[test] #[test]
fn test_intrdoduce_var() { fn test_intrdoduce_var_simple() {
check_action_range( check_action_range(
" "
fn foo() { fn foo() {
@ -192,6 +197,19 @@ fn foo() {
fn foo() { fn foo() {
let <|>var_name = 1 + 1; let <|>var_name = 1 + 1;
foo(var_name); foo(var_name);
}",
|file, range| introduce_variable(file, range).map(|f| f()),
);
}
#[test]
fn test_intrdoduce_var_expr_stmt() {
check_action_range(
"
fn foo() {
<|>1 + 1<|>;
}", "
fn foo() {
let <|>var_name = 1 + 1;
}", }",
|file, range| introduce_variable(file, range).map(|f| f()), |file, range| introduce_variable(file, range).map(|f| f()),
); );