increment.rs

  1use std::ops::Range;
  2
  3use editor::{scroll::autoscroll::Autoscroll, MultiBufferSnapshot, ToOffset, ToPoint};
  4use gpui::{impl_actions, AppContext, 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 init(cx: &mut AppContext) {
 28    cx.add_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    cx.add_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, |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                        if selection.is_empty() {
 82                            new_anchors.push((false, snapshot.anchor_after(range.end)))
 83                        }
 84                        edits.push((range, replace));
 85                    }
 86                }
 87            }
 88        }
 89        editor.transact(cx, |editor, cx| {
 90            editor.edit(edits, cx);
 91
 92            let snapshot = editor.buffer().read(cx).snapshot(cx);
 93            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 94                let mut new_ranges = Vec::new();
 95                for (visual, anchor) in new_anchors.iter() {
 96                    let mut point = anchor.to_point(&snapshot);
 97                    if !*visual && point.column > 0 {
 98                        point.column -= 1;
 99                        point = snapshot.clip_point(point, Bias::Left)
100                    }
101                    new_ranges.push(point..point);
102                }
103                s.select_ranges(new_ranges)
104            })
105        });
106    });
107    vim.switch_mode(Mode::Normal, true, cx)
108}
109
110fn find_number(
111    snapshot: &MultiBufferSnapshot,
112    start: Point,
113) -> Option<(Range<Point>, String, u32)> {
114    let mut offset = start.to_offset(snapshot);
115
116    // go backwards to the start of any number the selection is within
117    for ch in snapshot.reversed_chars_at(offset) {
118        if ch.is_ascii_digit() || ch == '-' || ch == 'b' || ch == 'x' {
119            offset -= ch.len_utf8();
120            continue;
121        }
122        break;
123    }
124
125    let mut begin = None;
126    let mut end = None;
127    let mut num = String::new();
128    let mut radix = 10;
129
130    let mut chars = snapshot.chars_at(offset).peekable();
131    // find the next number on the line (may start after the original cursor position)
132    while let Some(ch) = chars.next() {
133        if num == "0" && ch == 'b' && chars.peek().is_some() && chars.peek().unwrap().is_digit(2) {
134            radix = 2;
135            begin = None;
136            num = String::new();
137        }
138        if num == "0" && ch == 'x' && chars.peek().is_some() && chars.peek().unwrap().is_digit(16) {
139            radix = 16;
140            begin = None;
141            num = String::new();
142        }
143
144        if ch.is_digit(radix)
145            || (begin.is_none()
146                && ch == '-'
147                && chars.peek().is_some()
148                && chars.peek().unwrap().is_digit(radix))
149        {
150            if begin.is_none() {
151                begin = Some(offset);
152            }
153            num.push(ch);
154        } else {
155            if begin.is_some() {
156                end = Some(offset);
157                break;
158            } else if ch == '\n' {
159                break;
160            }
161        }
162        offset += ch.len_utf8();
163    }
164    if let Some(begin) = begin {
165        let end = end.unwrap_or(offset);
166        Some((begin.to_point(snapshot)..end.to_point(snapshot), num, radix))
167    } else {
168        None
169    }
170}
171
172#[cfg(test)]
173mod test {
174    use indoc::indoc;
175
176    use crate::test::NeovimBackedTestContext;
177
178    #[gpui::test]
179    async fn test_increment(cx: &mut gpui::TestAppContext) {
180        let mut cx = NeovimBackedTestContext::new(cx).await;
181
182        cx.set_shared_state(indoc! {"
183            1ˇ2
184            "})
185            .await;
186
187        cx.simulate_shared_keystrokes(["ctrl-a"]).await;
188        cx.assert_shared_state(indoc! {"
189            1ˇ3
190            "})
191            .await;
192        cx.simulate_shared_keystrokes(["ctrl-x"]).await;
193        cx.assert_shared_state(indoc! {"
194            1ˇ2
195            "})
196            .await;
197
198        cx.simulate_shared_keystrokes(["9", "9", "ctrl-a"]).await;
199        cx.assert_shared_state(indoc! {"
200            11ˇ1
201            "})
202            .await;
203        cx.simulate_shared_keystrokes(["1", "1", "1", "ctrl-x"])
204            .await;
205        cx.assert_shared_state(indoc! {"
206            ˇ0
207            "})
208            .await;
209        cx.simulate_shared_keystrokes(["."]).await;
210        cx.assert_shared_state(indoc! {"
211            -11ˇ1
212            "})
213            .await;
214    }
215
216    #[gpui::test]
217    async fn test_increment_radix(cx: &mut gpui::TestAppContext) {
218        let mut cx = NeovimBackedTestContext::new(cx).await;
219
220        cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-a"], " total: 0x10ˇ0")
221            .await;
222        cx.assert_matches_neovim("ˇ total: 0xff", ["ctrl-x"], " total: 0xfˇe")
223            .await;
224        cx.assert_matches_neovim("ˇ total: 0xFF", ["ctrl-x"], " total: 0xFˇE")
225            .await;
226        cx.assert_matches_neovim("(ˇ0b10f)", ["ctrl-a"], "(0b1ˇ1f)")
227            .await;
228        cx.assert_matches_neovim("ˇ-1", ["ctrl-a"], "ˇ0").await;
229    }
230
231    #[gpui::test]
232    async fn test_increment_steps(cx: &mut gpui::TestAppContext) {
233        let mut cx = NeovimBackedTestContext::new(cx).await;
234
235        cx.set_shared_state(indoc! {"
236            ˇ1
237            1
238            1  2
239            1
240            1"})
241            .await;
242
243        cx.simulate_shared_keystrokes(["j", "v", "shift-g", "g", "ctrl-a"])
244            .await;
245        cx.assert_shared_state(indoc! {"
246            1
247            ˇ2
248            3  2
249            4
250            5"})
251            .await;
252        cx.simulate_shared_keystrokes(["shift-g", "ctrl-v", "g", "g", "g", "ctrl-x"])
253            .await;
254        cx.assert_shared_state(indoc! {"
255            ˇ0
256            0
257            0  2
258            0
259            0"})
260            .await;
261    }
262}