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