From 95cd2c645b853b8b31792a5f97a144676198927f Mon Sep 17 00:00:00 2001 From: Gokul Soumya Date: Sat, 4 Sep 2021 20:59:08 +0530 Subject: Refactor switch_case commands --- helix-term/src/commands.rs | 48 ++++++++++++++++++---------------------------- 1 file changed, 19 insertions(+), 29 deletions(-) (limited to 'helix-term/src') diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index cad8cf60..2fbed6b3 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -811,12 +811,25 @@ fn replace(cx: &mut Context) { }) } -fn switch_case(cx: &mut Context) { +fn switch_case_impl(cx: &mut Context, change_fn: F) +where + F: Fn(Cow) -> Tendril, +{ let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id); let transaction = Transaction::change_by_selection(doc.text(), selection, |range| { - let text: Tendril = range - .fragment(doc.text().slice(..)) + let text: Tendril = change_fn(range.fragment(doc.text().slice(..))); + + (range.from(), range.to(), Some(text)) + }); + + doc.apply(&transaction, view.id); + doc.append_changes_to_history(view.id); +} + +fn switch_case(cx: &mut Context) { + switch_case_impl(cx, |string| { + string .chars() .flat_map(|ch| { if ch.is_lowercase() { @@ -827,39 +840,16 @@ fn switch_case(cx: &mut Context) { vec![ch] } }) - .collect(); - - (range.from(), range.to(), Some(text)) + .collect() }); - - doc.apply(&transaction, view.id); - doc.append_changes_to_history(view.id); } fn switch_to_uppercase(cx: &mut Context) { - let (view, doc) = current!(cx.editor); - let selection = doc.selection(view.id); - let transaction = Transaction::change_by_selection(doc.text(), selection, |range| { - let text: Tendril = range.fragment(doc.text().slice(..)).to_uppercase().into(); - - (range.from(), range.to(), Some(text)) - }); - - doc.apply(&transaction, view.id); - doc.append_changes_to_history(view.id); + switch_case_impl(cx, |string| string.to_uppercase().into()); } fn switch_to_lowercase(cx: &mut Context) { - let (view, doc) = current!(cx.editor); - let selection = doc.selection(view.id); - let transaction = Transaction::change_by_selection(doc.text(), selection, |range| { - let text: Tendril = range.fragment(doc.text().slice(..)).to_lowercase().into(); - - (range.from(), range.to(), Some(text)) - }); - - doc.apply(&transaction, view.id); - doc.append_changes_to_history(view.id); + switch_case_impl(cx, |string| string.to_lowercase().into()); } pub fn scroll(cx: &mut Context, offset: usize, direction: Direction) { -- cgit v1.2.3-70-g09d2