increment.rs

  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    let ch0 = snapshot.chars_at(offset).next();
121    if ch0.as_ref().is_some_and(char::is_ascii_digit) || matches!(ch0, Some('-' | 'b' | 'x')) {
122        // go backwards to the start of any number the selection is within
123        for ch in snapshot.reversed_chars_at(offset) {
124            if ch.is_ascii_digit() || ch == '-' || ch == 'b' || ch == 'x' {
125                offset -= ch.len_utf8();
126                continue;
127            }
128            break;
129        }
130    }
131
132    let mut begin = None;
133    let mut end = None;
134    let mut num = String::new();
135    let mut radix = 10;
136
137    let mut chars = snapshot.chars_at(offset).peekable();
138    // find the next number on the line (may start after the original cursor position)
139    while let Some(ch) = chars.next() {
140        if num == "0" && ch == 'b' && chars.peek().is_some() && chars.peek().unwrap().is_digit(2) {
141            radix = 2;
142            begin = None;
143            num = String::new();
144        }
145        if num == "0" && ch == 'x' && chars.peek().is_some() && chars.peek().unwrap().is_digit(16) {
146            radix = 16;
147            begin = None;
148            num = String::new();
149        }
150
151        if ch.is_digit(radix)
152            || (begin.is_none()
153                && ch == '-'
154                && chars.peek().is_some()
155                && chars.peek().unwrap().is_digit(radix))
156        {
157            if begin.is_none() {
158                begin = Some(offset);
159            }
160            num.push(ch);
161        } else {
162            if begin.is_some() {
163                end = Some(offset);
164                break;
165            } else if ch == '\n' {
166                break;
167            }
168        }
169        offset += ch.len_utf8();
170    }
171    if let Some(begin) = begin {
172        let end = end.unwrap_or(offset);
173        Some((begin.to_point(snapshot)..end.to_point(snapshot), num, radix))
174    } else {
175        None
176    }
177}
178
179#[cfg(test)]
180mod test {
181    use indoc::indoc;
182
183    use crate::test::NeovimBackedTestContext;
184
185    #[gpui::test]
186    async fn test_increment(cx: &mut gpui::TestAppContext) {
187        let mut cx = NeovimBackedTestContext::new(cx).await;
188
189        cx.set_shared_state(indoc! {"
190            1ˇ2
191            "})
192            .await;
193
194        cx.simulate_shared_keystrokes(["ctrl-a"]).await;
195        cx.assert_shared_state(indoc! {"
196            1ˇ3
197            "})
198            .await;
199        cx.simulate_shared_keystrokes(["ctrl-x"]).await;
200        cx.assert_shared_state(indoc! {"
201            1ˇ2
202            "})
203            .await;
204
205        cx.simulate_shared_keystrokes(["9", "9", "ctrl-a"]).await;
206        cx.assert_shared_state(indoc! {"
207            11ˇ1
208            "})
209            .await;
210        cx.simulate_shared_keystrokes(["1", "1", "1", "ctrl-x"])
211            .await;
212        cx.assert_shared_state(indoc! {"
213            ˇ0
214            "})
215            .await;
216        cx.simulate_shared_keystrokes(["."]).await;
217        cx.assert_shared_state(indoc! {"
218            -11ˇ1
219            "})
220            .await;
221    }
222
223    #[gpui::test]
224    async fn test_increment_with_dot(cx: &mut gpui::TestAppContext) {
225        let mut cx = NeovimBackedTestContext::new(cx).await;
226
227        cx.set_shared_state(indoc! {"
228            1ˇ.2
229            "})
230            .await;
231
232        cx.simulate_shared_keystrokes(["ctrl-a"]).await;
233        cx.assert_shared_state(indoc! {"
234            1.ˇ3
235            "})
236            .await;
237        cx.simulate_shared_keystrokes(["ctrl-x"]).await;
238        cx.assert_shared_state(indoc! {"
239            1.ˇ2
240            "})
241            .await;
242    }
243
244    #[gpui::test]
245    async fn test_increment_with_two_dots(cx: &mut gpui::TestAppContext) {
246        let mut cx = NeovimBackedTestContext::new(cx).await;
247
248        cx.set_shared_state(indoc! {"
249            111.ˇ.2
250            "})
251            .await;
252
253        cx.simulate_shared_keystrokes(["ctrl-a"]).await;
254        cx.assert_shared_state(indoc! {"
255            111..ˇ3
256            "})
257            .await;
258        cx.simulate_shared_keystrokes(["ctrl-x"]).await;
259        cx.assert_shared_state(indoc! {"
260            111..ˇ2
261            "})
262            .await;
263    }
264
265    #[gpui::test]
266    async fn test_increment_radix(cx: &mut gpui::TestAppContext) {
267        let mut cx = NeovimBackedTestContext::new(cx).await;
268
269        cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-a"], " total: 0x10ˇ0")
270            .await;
271        cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-x"], " total: 0xfˇe")
272            .await;
273        cx.assert_matches_neovim("ˇ total: 0xFF", ["ctrl-x"], " total: 0xFˇE")
274            .await;
275        cx.assert_matches_neovim("(ˇ0b10f)", ["ctrl-a"], "(0b1ˇ1f)")
276            .await;
277        cx.assert_matches_neovim("ˇ-1", ["ctrl-a"], "ˇ0").await;
278        cx.assert_matches_neovim("banˇana", ["ctrl-a"], "banˇana")
279            .await;
280    }
281
282    #[gpui::test]
283    async fn test_increment_steps(cx: &mut gpui::TestAppContext) {
284        let mut cx = NeovimBackedTestContext::new(cx).await;
285
286        cx.set_shared_state(indoc! {"
287            ˇ1
288            1
289            1  2
290            1
291            1"})
292            .await;
293
294        cx.simulate_shared_keystrokes(["j", "v", "shift-g", "g", "ctrl-a"])
295            .await;
296        cx.assert_shared_state(indoc! {"
297            1
298            ˇ2
299            3  2
300            4
301            5"})
302            .await;
303
304        cx.simulate_shared_keystrokes(["shift-g", "ctrl-v", "g", "g"])
305            .await;
306        cx.assert_shared_state(indoc! {"
307            «1ˇ»
308            «2ˇ»
309            «3ˇ»  2
310            «4ˇ»
311            «5ˇ»"})
312            .await;
313
314        cx.simulate_shared_keystrokes(["g", "ctrl-x"]).await;
315        cx.assert_shared_state(indoc! {"
316            ˇ0
317            0
318            0  2
319            0
320            0"})
321            .await;
322    }
323}