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.shared_state().await.assert_eq(indoc! {"
196            1ˇ3
197            "});
198        cx.simulate_shared_keystrokes("ctrl-x").await;
199        cx.shared_state().await.assert_eq(indoc! {"
200            1ˇ2
201            "});
202
203        cx.simulate_shared_keystrokes("9 9 ctrl-a").await;
204        cx.shared_state().await.assert_eq(indoc! {"
205            11ˇ1
206            "});
207        cx.simulate_shared_keystrokes("1 1 1 ctrl-x").await;
208        cx.shared_state().await.assert_eq(indoc! {"
209            ˇ0
210            "});
211        cx.simulate_shared_keystrokes(".").await;
212        cx.shared_state().await.assert_eq(indoc! {"
213            -11ˇ1
214            "});
215    }
216
217    #[gpui::test]
218    async fn test_increment_with_dot(cx: &mut gpui::TestAppContext) {
219        let mut cx = NeovimBackedTestContext::new(cx).await;
220
221        cx.set_shared_state(indoc! {"
222            1ˇ.2
223            "})
224            .await;
225
226        cx.simulate_shared_keystrokes("ctrl-a").await;
227        cx.shared_state().await.assert_eq(indoc! {"
228            1.ˇ3
229            "});
230        cx.simulate_shared_keystrokes("ctrl-x").await;
231        cx.shared_state().await.assert_eq(indoc! {"
232            1.ˇ2
233            "});
234    }
235
236    #[gpui::test]
237    async fn test_increment_with_two_dots(cx: &mut gpui::TestAppContext) {
238        let mut cx = NeovimBackedTestContext::new(cx).await;
239
240        cx.set_shared_state(indoc! {"
241            111.ˇ.2
242            "})
243            .await;
244
245        cx.simulate_shared_keystrokes("ctrl-a").await;
246        cx.shared_state().await.assert_eq(indoc! {"
247            111..ˇ3
248            "});
249        cx.simulate_shared_keystrokes("ctrl-x").await;
250        cx.shared_state().await.assert_eq(indoc! {"
251            111..ˇ2
252            "});
253    }
254
255    #[gpui::test]
256    async fn test_increment_radix(cx: &mut gpui::TestAppContext) {
257        let mut cx = NeovimBackedTestContext::new(cx).await;
258
259        cx.simulate("ctrl-a", "ˇ total: 0xff")
260            .await
261            .assert_matches();
262        cx.simulate("ctrl-x", "ˇ total: 0xff")
263            .await
264            .assert_matches();
265        cx.simulate("ctrl-x", "ˇ total: 0xFF")
266            .await
267            .assert_matches();
268        cx.simulate("ctrl-a", "(ˇ0b10f)").await.assert_matches();
269        cx.simulate("ctrl-a", "ˇ-1").await.assert_matches();
270        cx.simulate("ctrl-a", "banˇana").await.assert_matches();
271    }
272
273    #[gpui::test]
274    async fn test_increment_steps(cx: &mut gpui::TestAppContext) {
275        let mut cx = NeovimBackedTestContext::new(cx).await;
276
277        cx.set_shared_state(indoc! {"
278            ˇ1
279            1
280            1  2
281            1
282            1"})
283            .await;
284
285        cx.simulate_shared_keystrokes("j v shift-g g ctrl-a").await;
286        cx.shared_state().await.assert_eq(indoc! {"
287            1
288            ˇ2
289            3  2
290            4
291            5"});
292
293        cx.simulate_shared_keystrokes("shift-g ctrl-v g g").await;
294        cx.shared_state().await.assert_eq(indoc! {"
295            «1ˇ»
296            «2ˇ»
297            «3ˇ»  2
298            «4ˇ»
299            «5ˇ»"});
300
301        cx.simulate_shared_keystrokes("g ctrl-x").await;
302        cx.shared_state().await.assert_eq(indoc! {"
303            ˇ0
304            0
305            0  2
306            0
307            0"});
308    }
309}