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 editor.buffer().update(cx, |buffer, cx| {
167 let text = snapshot
168 .text_for_range(range.start..range.end)
169 .flat_map(|s| s.chars())
170 .flat_map(transform)
171 .collect::<String>();
172
173 buffer.edit([(range, text)], None, cx)
174 })
175 }
176 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
177 s.select_ranges(cursor_positions)
178 })
179 });
180 });
181 self.switch_mode(Mode::Normal, true, cx)
182 }
183}
184
185#[cfg(test)]
186mod test {
187 use crate::{state::Mode, test::NeovimBackedTestContext};
188
189 #[gpui::test]
190 async fn test_change_case(cx: &mut gpui::TestAppContext) {
191 let mut cx = NeovimBackedTestContext::new(cx).await;
192 cx.set_shared_state("ˇabC\n").await;
193 cx.simulate_shared_keystrokes("~").await;
194 cx.shared_state().await.assert_eq("AˇbC\n");
195 cx.simulate_shared_keystrokes("2 ~").await;
196 cx.shared_state().await.assert_eq("ABˇc\n");
197
198 // works in visual mode
199 cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
200 cx.simulate_shared_keystrokes("~").await;
201 cx.shared_state().await.assert_eq("a😀CˇDé1*F\n");
202
203 // works with multibyte characters
204 cx.simulate_shared_keystrokes("~").await;
205 cx.set_shared_state("aˇC😀é1*F\n").await;
206 cx.simulate_shared_keystrokes("4 ~").await;
207 cx.shared_state().await.assert_eq("ac😀É1ˇ*F\n");
208
209 // works with line selections
210 cx.set_shared_state("abˇC\n").await;
211 cx.simulate_shared_keystrokes("shift-v ~").await;
212 cx.shared_state().await.assert_eq("ˇABc\n");
213
214 // works in visual block mode
215 cx.set_shared_state("ˇaa\nbb\ncc").await;
216 cx.simulate_shared_keystrokes("ctrl-v j ~").await;
217 cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
218
219 // works with multiple cursors (zed only)
220 cx.set_state("aˇßcdˇe\n", Mode::Normal);
221 cx.simulate_keystrokes("~");
222 cx.assert_state("aSSˇcdˇE\n", Mode::Normal);
223 }
224
225 #[gpui::test]
226 async fn test_convert_to_upper_case(cx: &mut gpui::TestAppContext) {
227 let mut cx = NeovimBackedTestContext::new(cx).await;
228 // works in visual mode
229 cx.set_shared_state("a😀C«dÉ1*fˇ»\n").await;
230 cx.simulate_shared_keystrokes("U").await;
231 cx.shared_state().await.assert_eq("a😀CˇDÉ1*F\n");
232
233 // works with line selections
234 cx.set_shared_state("abˇC\n").await;
235 cx.simulate_shared_keystrokes("shift-v U").await;
236 cx.shared_state().await.assert_eq("ˇABC\n");
237
238 // works in visual block mode
239 cx.set_shared_state("ˇaa\nbb\ncc").await;
240 cx.simulate_shared_keystrokes("ctrl-v j U").await;
241 cx.shared_state().await.assert_eq("ˇAa\nBb\ncc");
242 }
243
244 #[gpui::test]
245 async fn test_convert_to_lower_case(cx: &mut gpui::TestAppContext) {
246 let mut cx = NeovimBackedTestContext::new(cx).await;
247 // works in visual mode
248 cx.set_shared_state("A😀c«DÉ1*fˇ»\n").await;
249 cx.simulate_shared_keystrokes("u").await;
250 cx.shared_state().await.assert_eq("A😀cˇdé1*f\n");
251
252 // works with line selections
253 cx.set_shared_state("ABˇc\n").await;
254 cx.simulate_shared_keystrokes("shift-v u").await;
255 cx.shared_state().await.assert_eq("ˇabc\n");
256
257 // works in visual block mode
258 cx.set_shared_state("ˇAa\nBb\nCc").await;
259 cx.simulate_shared_keystrokes("ctrl-v j u").await;
260 cx.shared_state().await.assert_eq("ˇaa\nbb\nCc");
261 }
262
263 #[gpui::test]
264 async fn test_change_case_motion(cx: &mut gpui::TestAppContext) {
265 let mut cx = NeovimBackedTestContext::new(cx).await;
266
267 cx.set_shared_state("ˇabc def").await;
268 cx.simulate_shared_keystrokes("g shift-u w").await;
269 cx.shared_state().await.assert_eq("ˇABC def");
270
271 cx.simulate_shared_keystrokes("g u w").await;
272 cx.shared_state().await.assert_eq("ˇabc def");
273
274 cx.simulate_shared_keystrokes("g ~ w").await;
275 cx.shared_state().await.assert_eq("ˇABC def");
276
277 cx.simulate_shared_keystrokes(".").await;
278 cx.shared_state().await.assert_eq("ˇabc def");
279
280 cx.set_shared_state("abˇc def").await;
281 cx.simulate_shared_keystrokes("g ~ i w").await;
282 cx.shared_state().await.assert_eq("ˇABC def");
283
284 cx.simulate_shared_keystrokes(".").await;
285 cx.shared_state().await.assert_eq("ˇabc def");
286
287 cx.simulate_shared_keystrokes("g shift-u $").await;
288 cx.shared_state().await.assert_eq("ˇABC DEF");
289 }
290}