1use std::ops::Range;
2
3use editor::{scroll::Autoscroll, MultiBufferSnapshot, ToOffset, ToPoint};
4use gpui::{impl_actions, ViewContext, WindowContext};
5use language::{Bias, Point};
6use serde::Deserialize;
7use workspace::Workspace;
8
9use crate::{state::Mode, Vim};
10
11#[derive(Clone, Deserialize, PartialEq)]
12#[serde(rename_all = "camelCase")]
13struct Increment {
14 #[serde(default)]
15 step: bool,
16}
17
18#[derive(Clone, Deserialize, PartialEq)]
19#[serde(rename_all = "camelCase")]
20struct Decrement {
21 #[serde(default)]
22 step: bool,
23}
24
25impl_actions!(vim, [Increment, Decrement]);
26
27pub fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
28 workspace.register_action(|_: &mut Workspace, action: &Increment, cx| {
29 Vim::update(cx, |vim, cx| {
30 vim.record_current_action(cx);
31 let count = vim.take_count(cx).unwrap_or(1);
32 let step = if action.step { 1 } else { 0 };
33 increment(vim, count as i32, step, cx)
34 })
35 });
36 workspace.register_action(|_: &mut Workspace, action: &Decrement, cx| {
37 Vim::update(cx, |vim, cx| {
38 vim.record_current_action(cx);
39 let count = vim.take_count(cx).unwrap_or(1);
40 let step = if action.step { -1 } else { 0 };
41 increment(vim, count as i32 * -1, step, cx)
42 })
43 });
44}
45
46fn increment(vim: &mut Vim, mut delta: i32, step: i32, cx: &mut WindowContext) {
47 vim.update_active_editor(cx, |vim, editor, cx| {
48 let mut edits = Vec::new();
49 let mut new_anchors = Vec::new();
50
51 let snapshot = editor.buffer().read(cx).snapshot(cx);
52 for selection in editor.selections.all_adjusted(cx) {
53 if !selection.is_empty() {
54 if vim.state().mode != Mode::VisualBlock || new_anchors.is_empty() {
55 new_anchors.push((true, snapshot.anchor_before(selection.start)))
56 }
57 }
58 for row in selection.start.row..=selection.end.row {
59 let start = if row == selection.start.row {
60 selection.start
61 } else {
62 Point::new(row, 0)
63 };
64
65 if let Some((range, num, radix)) = find_number(&snapshot, start) {
66 if let Ok(val) = i32::from_str_radix(&num, radix) {
67 let result = val + delta;
68 delta += step;
69 let replace = match radix {
70 10 => format!("{}", result),
71 16 => {
72 if num.to_ascii_lowercase() == num {
73 format!("{:x}", result)
74 } else {
75 format!("{:X}", result)
76 }
77 }
78 2 => format!("{:b}", result),
79 _ => unreachable!(),
80 };
81 edits.push((range.clone(), replace));
82 }
83 if selection.is_empty() {
84 new_anchors.push((false, snapshot.anchor_after(range.end)))
85 }
86 } else {
87 if selection.is_empty() {
88 new_anchors.push((true, snapshot.anchor_after(start)))
89 }
90 }
91 }
92 }
93 editor.transact(cx, |editor, cx| {
94 editor.edit(edits, cx);
95
96 let snapshot = editor.buffer().read(cx).snapshot(cx);
97 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
98 let mut new_ranges = Vec::new();
99 for (visual, anchor) in new_anchors.iter() {
100 let mut point = anchor.to_point(&snapshot);
101 if !*visual && point.column > 0 {
102 point.column -= 1;
103 point = snapshot.clip_point(point, Bias::Left)
104 }
105 new_ranges.push(point..point);
106 }
107 s.select_ranges(new_ranges)
108 })
109 });
110 });
111 vim.switch_mode(Mode::Normal, true, cx)
112}
113
114fn find_number(
115 snapshot: &MultiBufferSnapshot,
116 start: Point,
117) -> Option<(Range<Point>, String, u32)> {
118 let mut offset = start.to_offset(snapshot);
119
120 // go backwards to the start of any number the selection is within
121 for ch in snapshot.reversed_chars_at(offset) {
122 if ch.is_ascii_digit() || ch == '-' || ch == 'b' || ch == 'x' {
123 offset -= ch.len_utf8();
124 continue;
125 }
126 break;
127 }
128
129 let mut begin = None;
130 let mut end = None;
131 let mut num = String::new();
132 let mut radix = 10;
133
134 let mut chars = snapshot.chars_at(offset).peekable();
135 // find the next number on the line (may start after the original cursor position)
136 while let Some(ch) = chars.next() {
137 if num == "0" && ch == 'b' && chars.peek().is_some() && chars.peek().unwrap().is_digit(2) {
138 radix = 2;
139 begin = None;
140 num = String::new();
141 }
142 if num == "0" && ch == 'x' && chars.peek().is_some() && chars.peek().unwrap().is_digit(16) {
143 radix = 16;
144 begin = None;
145 num = String::new();
146 }
147
148 if ch.is_digit(radix)
149 || (begin.is_none()
150 && ch == '-'
151 && chars.peek().is_some()
152 && chars.peek().unwrap().is_digit(radix))
153 {
154 if begin.is_none() {
155 begin = Some(offset);
156 }
157 num.push(ch);
158 } else {
159 if begin.is_some() {
160 end = Some(offset);
161 break;
162 } else if ch == '\n' {
163 break;
164 }
165 }
166 offset += ch.len_utf8();
167 }
168 if let Some(begin) = begin {
169 let end = end.unwrap_or(offset);
170 Some((begin.to_point(snapshot)..end.to_point(snapshot), num, radix))
171 } else {
172 None
173 }
174}
175
176#[cfg(test)]
177mod test {
178 use indoc::indoc;
179
180 use crate::test::NeovimBackedTestContext;
181
182 #[gpui::test]
183 async fn test_increment(cx: &mut gpui::TestAppContext) {
184 let mut cx = NeovimBackedTestContext::new(cx).await;
185
186 cx.set_shared_state(indoc! {"
187 1ˇ2
188 "})
189 .await;
190
191 cx.simulate_shared_keystrokes(["ctrl-a"]).await;
192 cx.assert_shared_state(indoc! {"
193 1ˇ3
194 "})
195 .await;
196 cx.simulate_shared_keystrokes(["ctrl-x"]).await;
197 cx.assert_shared_state(indoc! {"
198 1ˇ2
199 "})
200 .await;
201
202 cx.simulate_shared_keystrokes(["9", "9", "ctrl-a"]).await;
203 cx.assert_shared_state(indoc! {"
204 11ˇ1
205 "})
206 .await;
207 cx.simulate_shared_keystrokes(["1", "1", "1", "ctrl-x"])
208 .await;
209 cx.assert_shared_state(indoc! {"
210 ˇ0
211 "})
212 .await;
213 cx.simulate_shared_keystrokes(["."]).await;
214 cx.assert_shared_state(indoc! {"
215 -11ˇ1
216 "})
217 .await;
218 }
219
220 #[gpui::test]
221 async fn test_increment_radix(cx: &mut gpui::TestAppContext) {
222 let mut cx = NeovimBackedTestContext::new(cx).await;
223
224 cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-a"], " total: 0x10ˇ0")
225 .await;
226 cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-x"], " total: 0xfˇe")
227 .await;
228 cx.assert_matches_neovim("ˇ total: 0xFF", ["ctrl-x"], " total: 0xFˇE")
229 .await;
230 cx.assert_matches_neovim("(ˇ0b10f)", ["ctrl-a"], "(0b1ˇ1f)")
231 .await;
232 cx.assert_matches_neovim("ˇ-1", ["ctrl-a"], "ˇ0").await;
233 cx.assert_matches_neovim("banˇana", ["ctrl-a"], "banˇana")
234 .await;
235 }
236
237 #[gpui::test]
238 async fn test_increment_steps(cx: &mut gpui::TestAppContext) {
239 let mut cx = NeovimBackedTestContext::new(cx).await;
240
241 cx.set_shared_state(indoc! {"
242 ˇ1
243 1
244 1 2
245 1
246 1"})
247 .await;
248
249 cx.simulate_shared_keystrokes(["j", "v", "shift-g", "g", "ctrl-a"])
250 .await;
251 cx.assert_shared_state(indoc! {"
252 1
253 ˇ2
254 3 2
255 4
256 5"})
257 .await;
258
259 cx.simulate_shared_keystrokes(["shift-g", "ctrl-v", "g", "g"])
260 .await;
261 cx.assert_shared_state(indoc! {"
262 «1ˇ»
263 «2ˇ»
264 «3ˇ» 2
265 «4ˇ»
266 «5ˇ»"})
267 .await;
268
269 cx.simulate_shared_keystrokes(["g", "ctrl-x"]).await;
270 cx.assert_shared_state(indoc! {"
271 ˇ0
272 0
273 0 2
274 0
275 0"})
276 .await;
277 }
278}