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