convert.rs

  1use collections::HashMap;
  2use editor::{SelectionEffects, display_map::ToDisplayPoint};
  3use gpui::{Context, Window};
  4use language::{Bias, Point, SelectionGoal};
  5use multi_buffer::MultiBufferRow;
  6
  7use crate::{
  8    Vim,
  9    motion::Motion,
 10    normal::{ChangeCase, ConvertToLowerCase, ConvertToRot13, ConvertToRot47, ConvertToUpperCase},
 11    object::Object,
 12    state::Mode,
 13};
 14
 15pub enum ConvertTarget {
 16    LowerCase,
 17    UpperCase,
 18    OppositeCase,
 19    Rot13,
 20    Rot47,
 21}
 22
 23impl Vim {
 24    pub fn convert_motion(
 25        &mut self,
 26        motion: Motion,
 27        times: Option<usize>,
 28        forced_motion: bool,
 29        mode: ConvertTarget,
 30        window: &mut Window,
 31        cx: &mut Context<Self>,
 32    ) {
 33        self.stop_recording(cx);
 34        self.update_editor(window, cx, |_, editor, window, cx| {
 35            editor.set_clip_at_line_ends(false, cx);
 36            let text_layout_details = editor.text_layout_details(window);
 37            editor.transact(window, cx, |editor, window, cx| {
 38                let mut selection_starts: HashMap<_, _> = Default::default();
 39                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
 40                    s.move_with(|map, selection| {
 41                        let anchor = map.display_point_to_anchor(selection.head(), Bias::Left);
 42                        selection_starts.insert(selection.id, anchor);
 43                        motion.expand_selection(
 44                            map,
 45                            selection,
 46                            times,
 47                            &text_layout_details,
 48                            forced_motion,
 49                        );
 50                    });
 51                });
 52                match mode {
 53                    ConvertTarget::LowerCase => {
 54                        editor.convert_to_lower_case(&Default::default(), window, cx)
 55                    }
 56                    ConvertTarget::UpperCase => {
 57                        editor.convert_to_upper_case(&Default::default(), window, cx)
 58                    }
 59                    ConvertTarget::OppositeCase => {
 60                        editor.convert_to_opposite_case(&Default::default(), window, cx)
 61                    }
 62                    ConvertTarget::Rot13 => {
 63                        editor.convert_to_rot13(&Default::default(), window, cx)
 64                    }
 65                    ConvertTarget::Rot47 => {
 66                        editor.convert_to_rot47(&Default::default(), window, cx)
 67                    }
 68                }
 69                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
 70                    s.move_with(|map, selection| {
 71                        let anchor = selection_starts.remove(&selection.id).unwrap();
 72                        selection.collapse_to(anchor.to_display_point(map), SelectionGoal::None);
 73                    });
 74                });
 75            });
 76            editor.set_clip_at_line_ends(true, cx);
 77        });
 78    }
 79
 80    pub fn convert_object(
 81        &mut self,
 82        object: Object,
 83        around: bool,
 84        mode: ConvertTarget,
 85        times: Option<usize>,
 86        window: &mut Window,
 87        cx: &mut Context<Self>,
 88    ) {
 89        self.stop_recording(cx);
 90        self.update_editor(window, cx, |_, editor, window, cx| {
 91            editor.transact(window, cx, |editor, window, cx| {
 92                editor.set_clip_at_line_ends(false, cx);
 93                let mut original_positions: HashMap<_, _> = Default::default();
 94                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
 95                    s.move_with(|map, selection| {
 96                        object.expand_selection(map, selection, around, times);
 97                        original_positions.insert(
 98                            selection.id,
 99                            map.display_point_to_anchor(selection.start, Bias::Left),
100                        );
101                    });
102                });
103                match mode {
104                    ConvertTarget::LowerCase => {
105                        editor.convert_to_lower_case(&Default::default(), window, cx)
106                    }
107                    ConvertTarget::UpperCase => {
108                        editor.convert_to_upper_case(&Default::default(), window, cx)
109                    }
110                    ConvertTarget::OppositeCase => {
111                        editor.convert_to_opposite_case(&Default::default(), window, cx)
112                    }
113                    ConvertTarget::Rot13 => {
114                        editor.convert_to_rot13(&Default::default(), window, cx)
115                    }
116                    ConvertTarget::Rot47 => {
117                        editor.convert_to_rot47(&Default::default(), window, cx)
118                    }
119                }
120                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
121                    s.move_with(|map, selection| {
122                        let anchor = original_positions.remove(&selection.id).unwrap();
123                        selection.collapse_to(anchor.to_display_point(map), SelectionGoal::None);
124                    });
125                });
126                editor.set_clip_at_line_ends(true, cx);
127            });
128        });
129    }
130
131    pub fn change_case(&mut self, _: &ChangeCase, window: &mut Window, cx: &mut Context<Self>) {
132        self.manipulate_text(window, cx, |c| {
133            if c.is_lowercase() {
134                c.to_uppercase().collect::<Vec<char>>()
135            } else {
136                c.to_lowercase().collect::<Vec<char>>()
137            }
138        })
139    }
140
141    pub fn convert_to_upper_case(
142        &mut self,
143        _: &ConvertToUpperCase,
144        window: &mut Window,
145        cx: &mut Context<Self>,
146    ) {
147        self.manipulate_text(window, cx, |c| c.to_uppercase().collect::<Vec<char>>())
148    }
149
150    pub fn convert_to_lower_case(
151        &mut self,
152        _: &ConvertToLowerCase,
153        window: &mut Window,
154        cx: &mut Context<Self>,
155    ) {
156        self.manipulate_text(window, cx, |c| c.to_lowercase().collect::<Vec<char>>())
157    }
158
159    pub fn convert_to_rot13(
160        &mut self,
161        _: &ConvertToRot13,
162        window: &mut Window,
163        cx: &mut Context<Self>,
164    ) {
165        self.manipulate_text(window, cx, |c| {
166            vec![match c {
167                'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
168                'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
169                _ => c,
170            }]
171        })
172    }
173
174    pub fn convert_to_rot47(
175        &mut self,
176        _: &ConvertToRot47,
177        window: &mut Window,
178        cx: &mut Context<Self>,
179    ) {
180        self.manipulate_text(window, cx, |c| {
181            let code_point = c as u32;
182            if code_point >= 33 && code_point <= 126 {
183                return vec![char::from_u32(33 + ((code_point + 14) % 94)).unwrap()];
184            }
185            vec![c]
186        })
187    }
188
189    fn manipulate_text<F>(&mut self, window: &mut Window, cx: &mut Context<Self>, transform: F)
190    where
191        F: Fn(char) -> Vec<char> + Copy,
192    {
193        self.record_current_action(cx);
194        self.store_visual_marks(window, cx);
195        let count = Vim::take_count(cx).unwrap_or(1) as u32;
196        Vim::take_forced_motion(cx);
197
198        self.update_editor(window, cx, |vim, editor, window, cx| {
199            let mut ranges = Vec::new();
200            let mut cursor_positions = Vec::new();
201            let snapshot = editor.buffer().read(cx).snapshot(cx);
202            for selection in editor.selections.all_adjusted(cx) {
203                match vim.mode {
204                    Mode::Visual | Mode::VisualLine => {
205                        ranges.push(selection.start..selection.end);
206                        cursor_positions.push(selection.start..selection.start);
207                    }
208                    Mode::VisualBlock => {
209                        ranges.push(selection.start..selection.end);
210                        if cursor_positions.is_empty() {
211                            cursor_positions.push(selection.start..selection.start);
212                        }
213                    }
214
215                    Mode::HelixNormal => {}
216                    Mode::Insert | Mode::Normal | Mode::Replace => {
217                        let start = selection.start;
218                        let mut end = start;
219                        for _ in 0..count {
220                            end = snapshot.clip_point(end + Point::new(0, 1), Bias::Right);
221                        }
222                        ranges.push(start..end);
223
224                        if end.column == snapshot.line_len(MultiBufferRow(end.row))
225                            && end.column > 0
226                        {
227                            end = snapshot.clip_point(end - Point::new(0, 1), Bias::Left);
228                        }
229                        cursor_positions.push(end..end)
230                    }
231                }
232            }
233            editor.transact(window, cx, |editor, window, cx| {
234                for range in ranges.into_iter().rev() {
235                    let snapshot = editor.buffer().read(cx).snapshot(cx);
236                    let text = snapshot
237                        .text_for_range(range.start..range.end)
238                        .flat_map(|s| s.chars())
239                        .flat_map(transform)
240                        .collect::<String>();
241                    editor.edit([(range, text)], cx)
242                }
243                editor.change_selections(Default::default(), window, cx, |s| {
244                    s.select_ranges(cursor_positions)
245                })
246            });
247        });
248        self.switch_mode(Mode::Normal, true, window, cx)
249    }
250}
251
252#[cfg(test)]
253mod test {
254    use crate::{state::Mode, test::NeovimBackedTestContext};
255
256    #[gpui::test]
257    async fn test_change_case(cx: &mut gpui::TestAppContext) {
258        let mut cx = NeovimBackedTestContext::new(cx).await;
259        cx.set_shared_state("ˇabC\n").await;
260        cx.simulate_shared_keystrokes("~").await;
261        cx.shared_state().await.assert_eq("AˇbC\n");
262        cx.simulate_shared_keystrokes("2 ~").await;
263        cx.shared_state().await.assert_eq("ABˇc\n");
264
265        // works in visual mode
266        cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
267        cx.simulate_shared_keystrokes("~").await;
268        cx.shared_state().await.assert_eq("a😀CˇDé1*F\n");
269
270        // works with multibyte characters
271        cx.simulate_shared_keystrokes("~").await;
272        cx.set_shared_state("aˇC😀é1*F\n").await;
273        cx.simulate_shared_keystrokes("4 ~").await;
274        cx.shared_state().await.assert_eq("ac😀É1ˇ*F\n");
275
276        // works with line selections
277        cx.set_shared_state("abˇC\n").await;
278        cx.simulate_shared_keystrokes("shift-v ~").await;
279        cx.shared_state().await.assert_eq("ˇABc\n");
280
281        // works in visual block mode
282        cx.set_shared_state("ˇaa\nbb\ncc").await;
283        cx.simulate_shared_keystrokes("ctrl-v j ~").await;
284        cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
285
286        // works with multiple cursors (zed only)
287        cx.set_state("aˇßcdˇe\n", Mode::Normal);
288        cx.simulate_keystrokes("~");
289        cx.assert_state("aSSˇcdˇE\n", Mode::Normal);
290    }
291
292    #[gpui::test]
293    async fn test_convert_to_upper_case(cx: &mut gpui::TestAppContext) {
294        let mut cx = NeovimBackedTestContext::new(cx).await;
295        // works in visual mode
296        cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
297        cx.simulate_shared_keystrokes("shift-u").await;
298        cx.shared_state().await.assert_eq("a😀CˇDÉ1*F\n");
299
300        // works with line selections
301        cx.set_shared_state("abˇC\n").await;
302        cx.simulate_shared_keystrokes("shift-v shift-u").await;
303        cx.shared_state().await.assert_eq("ˇABC\n");
304
305        // works in visual block mode
306        cx.set_shared_state("ˇaa\nbb\ncc").await;
307        cx.simulate_shared_keystrokes("ctrl-v j shift-u").await;
308        cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
309    }
310
311    #[gpui::test]
312    async fn test_convert_to_lower_case(cx: &mut gpui::TestAppContext) {
313        let mut cx = NeovimBackedTestContext::new(cx).await;
314        // works in visual mode
315        cx.set_shared_state("A😀c«DÉ1*fˇ»\n").await;
316        cx.simulate_shared_keystrokes("u").await;
317        cx.shared_state().await.assert_eq("A😀cˇdé1*f\n");
318
319        // works with line selections
320        cx.set_shared_state("ABˇc\n").await;
321        cx.simulate_shared_keystrokes("shift-v u").await;
322        cx.shared_state().await.assert_eq("ˇabc\n");
323
324        // works in visual block mode
325        cx.set_shared_state("ˇAa\nBb\nCc").await;
326        cx.simulate_shared_keystrokes("ctrl-v j u").await;
327        cx.shared_state().await.assert_eq("ˇaa\nbb\nCc");
328    }
329
330    #[gpui::test]
331    async fn test_change_case_motion(cx: &mut gpui::TestAppContext) {
332        let mut cx = NeovimBackedTestContext::new(cx).await;
333
334        cx.set_shared_state("ˇabc def").await;
335        cx.simulate_shared_keystrokes("g shift-u w").await;
336        cx.shared_state().await.assert_eq("ˇABC def");
337
338        cx.simulate_shared_keystrokes("g u w").await;
339        cx.shared_state().await.assert_eq("ˇabc def");
340
341        cx.simulate_shared_keystrokes("g ~ w").await;
342        cx.shared_state().await.assert_eq("ˇABC def");
343
344        cx.simulate_shared_keystrokes(".").await;
345        cx.shared_state().await.assert_eq("ˇabc def");
346
347        cx.set_shared_state("abˇc def").await;
348        cx.simulate_shared_keystrokes("g ~ i w").await;
349        cx.shared_state().await.assert_eq("ˇABC def");
350
351        cx.simulate_shared_keystrokes(".").await;
352        cx.shared_state().await.assert_eq("ˇabc def");
353
354        cx.simulate_shared_keystrokes("g shift-u $").await;
355        cx.shared_state().await.assert_eq("ˇABC DEF");
356    }
357
358    #[gpui::test]
359    async fn test_change_case_motion_object(cx: &mut gpui::TestAppContext) {
360        let mut cx = NeovimBackedTestContext::new(cx).await;
361
362        cx.set_shared_state("abc dˇef\n").await;
363        cx.simulate_shared_keystrokes("g shift-u i w").await;
364        cx.shared_state().await.assert_eq("abc ˇDEF\n");
365    }
366
367    #[gpui::test]
368    async fn test_convert_to_rot13(cx: &mut gpui::TestAppContext) {
369        let mut cx = NeovimBackedTestContext::new(cx).await;
370        // works in visual mode
371        cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
372        cx.simulate_shared_keystrokes("g ?").await;
373        cx.shared_state().await.assert_eq("a😀CˇqÉ1*s\n");
374
375        // works with line selections
376        cx.set_shared_state("abˇC\n").await;
377        cx.simulate_shared_keystrokes("shift-v g ?").await;
378        cx.shared_state().await.assert_eq("ˇnoP\n");
379
380        // works in visual block mode
381        cx.set_shared_state("ˇaa\nbb\ncc").await;
382        cx.simulate_shared_keystrokes("ctrl-v j g ?").await;
383        cx.shared_state().await.assert_eq("ˇna\nob\ncc");
384    }
385
386    #[gpui::test]
387    async fn test_change_rot13_motion(cx: &mut gpui::TestAppContext) {
388        let mut cx = NeovimBackedTestContext::new(cx).await;
389
390        cx.set_shared_state("ˇabc def").await;
391        cx.simulate_shared_keystrokes("g ? w").await;
392        cx.shared_state().await.assert_eq("ˇnop def");
393
394        cx.simulate_shared_keystrokes("g ? w").await;
395        cx.shared_state().await.assert_eq("ˇabc def");
396
397        cx.simulate_shared_keystrokes(".").await;
398        cx.shared_state().await.assert_eq("ˇnop def");
399
400        cx.set_shared_state("abˇc def").await;
401        cx.simulate_shared_keystrokes("g ? i w").await;
402        cx.shared_state().await.assert_eq("ˇnop def");
403
404        cx.simulate_shared_keystrokes(".").await;
405        cx.shared_state().await.assert_eq("ˇabc def");
406
407        cx.simulate_shared_keystrokes("g ? $").await;
408        cx.shared_state().await.assert_eq("ˇnop qrs");
409    }
410
411    #[gpui::test]
412    async fn test_change_rot13_object(cx: &mut gpui::TestAppContext) {
413        let mut cx = NeovimBackedTestContext::new(cx).await;
414
415        cx.set_shared_state("ˇabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
416            .await;
417        cx.simulate_shared_keystrokes("g ? i w").await;
418        cx.shared_state()
419            .await
420            .assert_eq("ˇnopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM");
421    }
422}