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