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(cx, |_, editor, 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(cx, |_, editor, 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(cx, |vim, editor, 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 | Mode::HelixSelect => {
216 if selection.is_empty() {
217 // Handle empty selection by operating on the whole word
218 let (word_range, _) = snapshot.surrounding_word(selection.start, false);
219 let word_start = snapshot.offset_to_point(word_range.start);
220 let word_end = snapshot.offset_to_point(word_range.end);
221 ranges.push(word_start..word_end);
222 cursor_positions.push(selection.start..selection.start);
223 } else {
224 ranges.push(selection.start..selection.end);
225 cursor_positions.push(selection.start..selection.end);
226 }
227 }
228 Mode::Insert | Mode::Normal | Mode::Replace => {
229 let start = selection.start;
230 let mut end = start;
231 for _ in 0..count {
232 end = snapshot.clip_point(end + Point::new(0, 1), Bias::Right);
233 }
234 ranges.push(start..end);
235
236 if end.column == snapshot.line_len(MultiBufferRow(end.row))
237 && end.column > 0
238 {
239 end = snapshot.clip_point(end - Point::new(0, 1), Bias::Left);
240 }
241 cursor_positions.push(end..end)
242 }
243 }
244 }
245 editor.transact(window, cx, |editor, window, cx| {
246 for range in ranges.into_iter().rev() {
247 let snapshot = editor.buffer().read(cx).snapshot(cx);
248 let text = snapshot
249 .text_for_range(range.start..range.end)
250 .flat_map(|s| s.chars())
251 .flat_map(transform)
252 .collect::<String>();
253 editor.edit([(range, text)], cx)
254 }
255 editor.change_selections(Default::default(), window, cx, |s| {
256 s.select_ranges(cursor_positions)
257 })
258 });
259 });
260 if self.mode != Mode::HelixNormal {
261 self.switch_mode(Mode::Normal, true, window, cx)
262 }
263 }
264}
265
266#[cfg(test)]
267mod test {
268 use crate::test::VimTestContext;
269
270 use crate::{state::Mode, test::NeovimBackedTestContext};
271
272 #[gpui::test]
273 async fn test_change_case(cx: &mut gpui::TestAppContext) {
274 let mut cx = NeovimBackedTestContext::new(cx).await;
275 cx.set_shared_state("ˇabC\n").await;
276 cx.simulate_shared_keystrokes("~").await;
277 cx.shared_state().await.assert_eq("AˇbC\n");
278 cx.simulate_shared_keystrokes("2 ~").await;
279 cx.shared_state().await.assert_eq("ABˇc\n");
280
281 // works in visual mode
282 cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
283 cx.simulate_shared_keystrokes("~").await;
284 cx.shared_state().await.assert_eq("a😀CˇDé1*F\n");
285
286 // works with multibyte characters
287 cx.simulate_shared_keystrokes("~").await;
288 cx.set_shared_state("aˇC😀é1*F\n").await;
289 cx.simulate_shared_keystrokes("4 ~").await;
290 cx.shared_state().await.assert_eq("ac😀É1ˇ*F\n");
291
292 // works with line selections
293 cx.set_shared_state("abˇC\n").await;
294 cx.simulate_shared_keystrokes("shift-v ~").await;
295 cx.shared_state().await.assert_eq("ˇABc\n");
296
297 // works in visual block mode
298 cx.set_shared_state("ˇaa\nbb\ncc").await;
299 cx.simulate_shared_keystrokes("ctrl-v j ~").await;
300 cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
301
302 // works with multiple cursors (zed only)
303 cx.set_state("aˇßcdˇe\n", Mode::Normal);
304 cx.simulate_keystrokes("~");
305 cx.assert_state("aSSˇcdˇE\n", Mode::Normal);
306 }
307
308 #[gpui::test]
309 async fn test_convert_to_upper_case(cx: &mut gpui::TestAppContext) {
310 let mut cx = NeovimBackedTestContext::new(cx).await;
311 // works in visual mode
312 cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
313 cx.simulate_shared_keystrokes("shift-u").await;
314 cx.shared_state().await.assert_eq("a😀CˇDÉ1*F\n");
315
316 // works with line selections
317 cx.set_shared_state("abˇC\n").await;
318 cx.simulate_shared_keystrokes("shift-v shift-u").await;
319 cx.shared_state().await.assert_eq("ˇABC\n");
320
321 // works in visual block mode
322 cx.set_shared_state("ˇaa\nbb\ncc").await;
323 cx.simulate_shared_keystrokes("ctrl-v j shift-u").await;
324 cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
325 }
326
327 #[gpui::test]
328 async fn test_convert_to_lower_case(cx: &mut gpui::TestAppContext) {
329 let mut cx = NeovimBackedTestContext::new(cx).await;
330 // works in visual mode
331 cx.set_shared_state("A😀c«DÉ1*fˇ»\n").await;
332 cx.simulate_shared_keystrokes("u").await;
333 cx.shared_state().await.assert_eq("A😀cˇdé1*f\n");
334
335 // works with line selections
336 cx.set_shared_state("ABˇc\n").await;
337 cx.simulate_shared_keystrokes("shift-v u").await;
338 cx.shared_state().await.assert_eq("ˇabc\n");
339
340 // works in visual block mode
341 cx.set_shared_state("ˇAa\nBb\nCc").await;
342 cx.simulate_shared_keystrokes("ctrl-v j u").await;
343 cx.shared_state().await.assert_eq("ˇaa\nbb\nCc");
344 }
345
346 #[gpui::test]
347 async fn test_change_case_motion(cx: &mut gpui::TestAppContext) {
348 let mut cx = NeovimBackedTestContext::new(cx).await;
349
350 cx.set_shared_state("ˇabc def").await;
351 cx.simulate_shared_keystrokes("g shift-u w").await;
352 cx.shared_state().await.assert_eq("ˇABC def");
353
354 cx.simulate_shared_keystrokes("g u w").await;
355 cx.shared_state().await.assert_eq("ˇabc def");
356
357 cx.simulate_shared_keystrokes("g ~ w").await;
358 cx.shared_state().await.assert_eq("ˇABC def");
359
360 cx.simulate_shared_keystrokes(".").await;
361 cx.shared_state().await.assert_eq("ˇabc def");
362
363 cx.set_shared_state("abˇc def").await;
364 cx.simulate_shared_keystrokes("g ~ i w").await;
365 cx.shared_state().await.assert_eq("ˇABC def");
366
367 cx.simulate_shared_keystrokes(".").await;
368 cx.shared_state().await.assert_eq("ˇabc def");
369
370 cx.simulate_shared_keystrokes("g shift-u $").await;
371 cx.shared_state().await.assert_eq("ˇABC DEF");
372 }
373
374 #[gpui::test]
375 async fn test_change_case_motion_object(cx: &mut gpui::TestAppContext) {
376 let mut cx = NeovimBackedTestContext::new(cx).await;
377
378 cx.set_shared_state("abc dˇef\n").await;
379 cx.simulate_shared_keystrokes("g shift-u i w").await;
380 cx.shared_state().await.assert_eq("abc ˇDEF\n");
381 }
382
383 #[gpui::test]
384 async fn test_convert_to_rot13(cx: &mut gpui::TestAppContext) {
385 let mut cx = NeovimBackedTestContext::new(cx).await;
386 // works in visual mode
387 cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
388 cx.simulate_shared_keystrokes("g ?").await;
389 cx.shared_state().await.assert_eq("a😀CˇqÉ1*s\n");
390
391 // works with line selections
392 cx.set_shared_state("abˇC\n").await;
393 cx.simulate_shared_keystrokes("shift-v g ?").await;
394 cx.shared_state().await.assert_eq("ˇnoP\n");
395
396 // works in visual block mode
397 cx.set_shared_state("ˇaa\nbb\ncc").await;
398 cx.simulate_shared_keystrokes("ctrl-v j g ?").await;
399 cx.shared_state().await.assert_eq("ˇna\nob\ncc");
400 }
401
402 #[gpui::test]
403 async fn test_change_rot13_motion(cx: &mut gpui::TestAppContext) {
404 let mut cx = NeovimBackedTestContext::new(cx).await;
405
406 cx.set_shared_state("ˇabc def").await;
407 cx.simulate_shared_keystrokes("g ? w").await;
408 cx.shared_state().await.assert_eq("ˇnop def");
409
410 cx.simulate_shared_keystrokes("g ? w").await;
411 cx.shared_state().await.assert_eq("ˇabc def");
412
413 cx.simulate_shared_keystrokes(".").await;
414 cx.shared_state().await.assert_eq("ˇnop def");
415
416 cx.set_shared_state("abˇc def").await;
417 cx.simulate_shared_keystrokes("g ? i w").await;
418 cx.shared_state().await.assert_eq("ˇnop def");
419
420 cx.simulate_shared_keystrokes(".").await;
421 cx.shared_state().await.assert_eq("ˇabc def");
422
423 cx.simulate_shared_keystrokes("g ? $").await;
424 cx.shared_state().await.assert_eq("ˇnop qrs");
425 }
426
427 #[gpui::test]
428 async fn test_change_rot13_object(cx: &mut gpui::TestAppContext) {
429 let mut cx = NeovimBackedTestContext::new(cx).await;
430
431 cx.set_shared_state("ˇabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
432 .await;
433 cx.simulate_shared_keystrokes("g ? i w").await;
434 cx.shared_state()
435 .await
436 .assert_eq("ˇnopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM");
437 }
438
439 #[gpui::test]
440 async fn test_change_case_helix_mode(cx: &mut gpui::TestAppContext) {
441 let mut cx = VimTestContext::new(cx, true).await;
442
443 // Explicit selection
444 cx.set_state("«hello worldˇ»", Mode::HelixNormal);
445 cx.simulate_keystrokes("~");
446 cx.assert_state("«HELLO WORLDˇ»", Mode::HelixNormal);
447
448 // Cursor-only (empty) selection
449 cx.set_state("The ˇquick brown", Mode::HelixNormal);
450 cx.simulate_keystrokes("~");
451 cx.assert_state("The ˇQUICK brown", Mode::HelixNormal);
452
453 // With `e` motion (which extends selection to end of word in Helix)
454 cx.set_state("The ˇquick brown fox", Mode::HelixNormal);
455 cx.simulate_keystrokes("e");
456 cx.simulate_keystrokes("~");
457 cx.assert_state("The «QUICKˇ» brown fox", Mode::HelixNormal);
458 }
459}