case.rs

  1use collections::HashMap;
  2use editor::{display_map::ToDisplayPoint, scroll::Autoscroll};
  3use gpui::ViewContext;
  4use language::{Bias, Point, SelectionGoal};
  5use multi_buffer::MultiBufferRow;
  6
  7use crate::{
  8    motion::Motion,
  9    normal::{ChangeCase, ConvertToLowerCase, ConvertToUpperCase},
 10    object::Object,
 11    state::Mode,
 12    Vim,
 13};
 14
 15pub enum CaseTarget {
 16    Lowercase,
 17    Uppercase,
 18    OppositeCase,
 19}
 20
 21impl Vim {
 22    pub fn change_case_motion(
 23        &mut self,
 24        motion: Motion,
 25        times: Option<usize>,
 26        mode: CaseTarget,
 27        cx: &mut ViewContext<Self>,
 28    ) {
 29        self.stop_recording(cx);
 30        self.update_editor(cx, |_, editor, cx| {
 31            let text_layout_details = editor.text_layout_details(cx);
 32            editor.transact(cx, |editor, cx| {
 33                let mut selection_starts: HashMap<_, _> = Default::default();
 34                editor.change_selections(None, cx, |s| {
 35                    s.move_with(|map, selection| {
 36                        let anchor = map.display_point_to_anchor(selection.head(), Bias::Left);
 37                        selection_starts.insert(selection.id, anchor);
 38                        motion.expand_selection(map, selection, times, false, &text_layout_details);
 39                    });
 40                });
 41                match mode {
 42                    CaseTarget::Lowercase => editor.convert_to_lower_case(&Default::default(), cx),
 43                    CaseTarget::Uppercase => editor.convert_to_upper_case(&Default::default(), cx),
 44                    CaseTarget::OppositeCase => {
 45                        editor.convert_to_opposite_case(&Default::default(), cx)
 46                    }
 47                }
 48                editor.change_selections(None, cx, |s| {
 49                    s.move_with(|map, selection| {
 50                        let anchor = selection_starts.remove(&selection.id).unwrap();
 51                        selection.collapse_to(anchor.to_display_point(map), SelectionGoal::None);
 52                    });
 53                });
 54            });
 55        });
 56    }
 57
 58    pub fn change_case_object(
 59        &mut self,
 60        object: Object,
 61        around: bool,
 62        mode: CaseTarget,
 63        cx: &mut ViewContext<Self>,
 64    ) {
 65        self.stop_recording(cx);
 66        self.update_editor(cx, |_, editor, cx| {
 67            editor.transact(cx, |editor, cx| {
 68                let mut original_positions: HashMap<_, _> = Default::default();
 69                editor.change_selections(None, cx, |s| {
 70                    s.move_with(|map, selection| {
 71                        object.expand_selection(map, selection, around);
 72                        original_positions.insert(
 73                            selection.id,
 74                            map.display_point_to_anchor(selection.start, Bias::Left),
 75                        );
 76                    });
 77                });
 78                match mode {
 79                    CaseTarget::Lowercase => editor.convert_to_lower_case(&Default::default(), cx),
 80                    CaseTarget::Uppercase => editor.convert_to_upper_case(&Default::default(), cx),
 81                    CaseTarget::OppositeCase => {
 82                        editor.convert_to_opposite_case(&Default::default(), cx)
 83                    }
 84                }
 85                editor.change_selections(None, cx, |s| {
 86                    s.move_with(|map, selection| {
 87                        let anchor = original_positions.remove(&selection.id).unwrap();
 88                        selection.collapse_to(anchor.to_display_point(map), SelectionGoal::None);
 89                    });
 90                });
 91            });
 92        });
 93    }
 94
 95    pub fn change_case(&mut self, _: &ChangeCase, cx: &mut ViewContext<Self>) {
 96        self.manipulate_text(cx, |c| {
 97            if c.is_lowercase() {
 98                c.to_uppercase().collect::<Vec<char>>()
 99            } else {
100                c.to_lowercase().collect::<Vec<char>>()
101            }
102        })
103    }
104
105    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
106        self.manipulate_text(cx, |c| c.to_uppercase().collect::<Vec<char>>())
107    }
108
109    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
110        self.manipulate_text(cx, |c| c.to_lowercase().collect::<Vec<char>>())
111    }
112
113    fn manipulate_text<F>(&mut self, cx: &mut ViewContext<Self>, transform: F)
114    where
115        F: Fn(char) -> Vec<char> + Copy,
116    {
117        self.record_current_action(cx);
118        self.store_visual_marks(cx);
119        let count = self.take_count(cx).unwrap_or(1) as u32;
120
121        self.update_editor(cx, |vim, editor, cx| {
122            let mut ranges = Vec::new();
123            let mut cursor_positions = Vec::new();
124            let snapshot = editor.buffer().read(cx).snapshot(cx);
125            for selection in editor.selections.all::<Point>(cx) {
126                match vim.mode {
127                    Mode::VisualLine => {
128                        let start = Point::new(selection.start.row, 0);
129                        let end = Point::new(
130                            selection.end.row,
131                            snapshot.line_len(MultiBufferRow(selection.end.row)),
132                        );
133                        ranges.push(start..end);
134                        cursor_positions.push(start..start);
135                    }
136                    Mode::Visual => {
137                        ranges.push(selection.start..selection.end);
138                        cursor_positions.push(selection.start..selection.start);
139                    }
140                    Mode::VisualBlock => {
141                        ranges.push(selection.start..selection.end);
142                        if cursor_positions.is_empty() {
143                            cursor_positions.push(selection.start..selection.start);
144                        }
145                    }
146                    Mode::Insert | Mode::Normal | Mode::Replace => {
147                        let start = selection.start;
148                        let mut end = start;
149                        for _ in 0..count {
150                            end = snapshot.clip_point(end + Point::new(0, 1), Bias::Right);
151                        }
152                        ranges.push(start..end);
153
154                        if end.column == snapshot.line_len(MultiBufferRow(end.row)) {
155                            end = snapshot.clip_point(end - Point::new(0, 1), Bias::Left);
156                        }
157                        cursor_positions.push(end..end)
158                    }
159                }
160            }
161            editor.transact(cx, |editor, cx| {
162                for range in ranges.into_iter().rev() {
163                    let snapshot = editor.buffer().read(cx).snapshot(cx);
164                    editor.buffer().update(cx, |buffer, cx| {
165                        let text = snapshot
166                            .text_for_range(range.start..range.end)
167                            .flat_map(|s| s.chars())
168                            .flat_map(transform)
169                            .collect::<String>();
170
171                        buffer.edit([(range, text)], None, cx)
172                    })
173                }
174                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
175                    s.select_ranges(cursor_positions)
176                })
177            });
178        });
179        self.switch_mode(Mode::Normal, true, cx)
180    }
181}
182
183#[cfg(test)]
184mod test {
185    use crate::{state::Mode, test::NeovimBackedTestContext};
186
187    #[gpui::test]
188    async fn test_change_case(cx: &mut gpui::TestAppContext) {
189        let mut cx = NeovimBackedTestContext::new(cx).await;
190        cx.set_shared_state("ˇabC\n").await;
191        cx.simulate_shared_keystrokes("~").await;
192        cx.shared_state().await.assert_eq("AˇbC\n");
193        cx.simulate_shared_keystrokes("2 ~").await;
194        cx.shared_state().await.assert_eq("ABˇc\n");
195
196        // works in visual mode
197        cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
198        cx.simulate_shared_keystrokes("~").await;
199        cx.shared_state().await.assert_eq("a😀CˇDé1*F\n");
200
201        // works with multibyte characters
202        cx.simulate_shared_keystrokes("~").await;
203        cx.set_shared_state("aˇC😀é1*F\n").await;
204        cx.simulate_shared_keystrokes("4 ~").await;
205        cx.shared_state().await.assert_eq("ac😀É1ˇ*F\n");
206
207        // works with line selections
208        cx.set_shared_state("abˇC\n").await;
209        cx.simulate_shared_keystrokes("shift-v ~").await;
210        cx.shared_state().await.assert_eq("ˇABc\n");
211
212        // works in visual block mode
213        cx.set_shared_state("ˇaa\nbb\ncc").await;
214        cx.simulate_shared_keystrokes("ctrl-v j ~").await;
215        cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
216
217        // works with multiple cursors (zed only)
218        cx.set_state("aˇßcdˇe\n", Mode::Normal);
219        cx.simulate_keystrokes("~");
220        cx.assert_state("aSSˇcdˇE\n", Mode::Normal);
221    }
222
223    #[gpui::test]
224    async fn test_convert_to_upper_case(cx: &mut gpui::TestAppContext) {
225        let mut cx = NeovimBackedTestContext::new(cx).await;
226        // works in visual mode
227        cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
228        cx.simulate_shared_keystrokes("U").await;
229        cx.shared_state().await.assert_eq("a😀CˇDÉ1*F\n");
230
231        // works with line selections
232        cx.set_shared_state("abˇC\n").await;
233        cx.simulate_shared_keystrokes("shift-v U").await;
234        cx.shared_state().await.assert_eq("ˇABC\n");
235
236        // works in visual block mode
237        cx.set_shared_state("ˇaa\nbb\ncc").await;
238        cx.simulate_shared_keystrokes("ctrl-v j U").await;
239        cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
240    }
241
242    #[gpui::test]
243    async fn test_convert_to_lower_case(cx: &mut gpui::TestAppContext) {
244        let mut cx = NeovimBackedTestContext::new(cx).await;
245        // works in visual mode
246        cx.set_shared_state("A😀c«DÉ1*fˇ»\n").await;
247        cx.simulate_shared_keystrokes("u").await;
248        cx.shared_state().await.assert_eq("A😀cˇdé1*f\n");
249
250        // works with line selections
251        cx.set_shared_state("ABˇc\n").await;
252        cx.simulate_shared_keystrokes("shift-v u").await;
253        cx.shared_state().await.assert_eq("ˇabc\n");
254
255        // works in visual block mode
256        cx.set_shared_state("ˇAa\nBb\nCc").await;
257        cx.simulate_shared_keystrokes("ctrl-v j u").await;
258        cx.shared_state().await.assert_eq("ˇaa\nbb\nCc");
259    }
260
261    #[gpui::test]
262    async fn test_change_case_motion(cx: &mut gpui::TestAppContext) {
263        let mut cx = NeovimBackedTestContext::new(cx).await;
264        // works in visual mode
265        cx.set_shared_state("ˇabc def").await;
266        cx.simulate_shared_keystrokes("g shift-u w").await;
267        cx.shared_state().await.assert_eq("ˇABC def");
268
269        cx.simulate_shared_keystrokes("g u w").await;
270        cx.shared_state().await.assert_eq("ˇabc def");
271
272        cx.simulate_shared_keystrokes("g ~ w").await;
273        cx.shared_state().await.assert_eq("ˇABC def");
274
275        cx.simulate_shared_keystrokes(".").await;
276        cx.shared_state().await.assert_eq("ˇabc def");
277
278        cx.set_shared_state("abˇc def").await;
279        cx.simulate_shared_keystrokes("g ~ i w").await;
280        cx.shared_state().await.assert_eq("ˇABC def");
281
282        cx.simulate_shared_keystrokes(".").await;
283        cx.shared_state().await.assert_eq("ˇabc def");
284    }
285}