paste.rs

  1use std::{borrow::Cow, cmp};
  2
  3use editor::{
  4    display_map::ToDisplayPoint, movement, scroll::autoscroll::Autoscroll, ClipboardSelection,
  5    DisplayPoint,
  6};
  7use gpui::{impl_actions, AppContext, ViewContext};
  8use language::{Bias, SelectionGoal};
  9use serde::Deserialize;
 10use workspace::Workspace;
 11
 12use crate::{state::Mode, utils::copy_selections_content, Vim};
 13
 14#[derive(Clone, Deserialize, PartialEq)]
 15#[serde(rename_all = "camelCase")]
 16struct Paste {
 17    #[serde(default)]
 18    before: bool,
 19    #[serde(default)]
 20    preserve_clipboard: bool,
 21}
 22
 23impl_actions!(vim, [Paste]);
 24
 25pub(crate) fn init(cx: &mut AppContext) {
 26    cx.add_action(paste);
 27}
 28
 29fn paste(_: &mut Workspace, action: &Paste, cx: &mut ViewContext<Workspace>) {
 30    Vim::update(cx, |vim, cx| {
 31        vim.record_current_action(cx);
 32        vim.update_active_editor(cx, |editor, cx| {
 33            editor.transact(cx, |editor, cx| {
 34                editor.set_clip_at_line_ends(false, cx);
 35
 36                let Some(item) = cx.read_from_clipboard() else {
 37                    return;
 38                };
 39                let clipboard_text = Cow::Borrowed(item.text());
 40                if clipboard_text.is_empty() {
 41                    return;
 42                }
 43
 44                if !action.preserve_clipboard && vim.state().mode.is_visual() {
 45                    copy_selections_content(editor, vim.state().mode == Mode::VisualLine, cx);
 46                }
 47
 48                // if we are copying from multi-cursor (of visual block mode), we want
 49                // to
 50                let clipboard_selections =
 51                    item.metadata::<Vec<ClipboardSelection>>()
 52                        .filter(|clipboard_selections| {
 53                            clipboard_selections.len() > 1 && vim.state().mode != Mode::VisualLine
 54                        });
 55
 56                let (display_map, current_selections) = editor.selections.all_adjusted_display(cx);
 57
 58                // unlike zed, if you have a multi-cursor selection from vim block mode,
 59                // pasting it will paste it on subsequent lines, even if you don't yet
 60                // have a cursor there.
 61                let mut selections_to_process = Vec::new();
 62                let mut i = 0;
 63                while i < current_selections.len() {
 64                    selections_to_process
 65                        .push((current_selections[i].start..current_selections[i].end, true));
 66                    i += 1;
 67                }
 68                if let Some(clipboard_selections) = clipboard_selections.as_ref() {
 69                    let left = current_selections
 70                        .iter()
 71                        .map(|selection| cmp::min(selection.start.column(), selection.end.column()))
 72                        .min()
 73                        .unwrap();
 74                    let mut row = current_selections.last().unwrap().end.row() + 1;
 75                    while i < clipboard_selections.len() {
 76                        let cursor =
 77                            display_map.clip_point(DisplayPoint::new(row, left), Bias::Left);
 78                        selections_to_process.push((cursor..cursor, false));
 79                        i += 1;
 80                        row += 1;
 81                    }
 82                }
 83
 84                let first_selection_indent_column =
 85                    clipboard_selections.as_ref().and_then(|zed_selections| {
 86                        zed_selections
 87                            .first()
 88                            .map(|selection| selection.first_line_indent)
 89                    });
 90                let before = action.before || vim.state().mode == Mode::VisualLine;
 91
 92                let mut edits = Vec::new();
 93                let mut new_selections = Vec::new();
 94                let mut original_indent_columns = Vec::new();
 95                let mut start_offset = 0;
 96
 97                for (ix, (selection, preserve)) in selections_to_process.iter().enumerate() {
 98                    let (mut to_insert, original_indent_column) =
 99                        if let Some(clipboard_selections) = &clipboard_selections {
100                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
101                                let end_offset = start_offset + clipboard_selection.len;
102                                let text = clipboard_text[start_offset..end_offset].to_string();
103                                start_offset = end_offset + 1;
104                                (text, Some(clipboard_selection.first_line_indent))
105                            } else {
106                                ("".to_string(), first_selection_indent_column)
107                            }
108                        } else {
109                            (clipboard_text.to_string(), first_selection_indent_column)
110                        };
111                    let line_mode = to_insert.ends_with("\n");
112                    let is_multiline = to_insert.contains("\n");
113
114                    if line_mode && !before {
115                        if selection.is_empty() {
116                            to_insert =
117                                "\n".to_owned() + &to_insert[..to_insert.len() - "\n".len()];
118                        } else {
119                            to_insert = "\n".to_owned() + &to_insert;
120                        }
121                    } else if !line_mode && vim.state().mode == Mode::VisualLine {
122                        to_insert = to_insert + "\n";
123                    }
124
125                    let display_range = if !selection.is_empty() {
126                        selection.start..selection.end
127                    } else if line_mode {
128                        let point = if before {
129                            movement::line_beginning(&display_map, selection.start, false)
130                        } else {
131                            movement::line_end(&display_map, selection.start, false)
132                        };
133                        point..point
134                    } else {
135                        let point = if before {
136                            selection.start
137                        } else {
138                            movement::saturating_right(&display_map, selection.start)
139                        };
140                        point..point
141                    };
142
143                    let point_range = display_range.start.to_point(&display_map)
144                        ..display_range.end.to_point(&display_map);
145                    let anchor = if is_multiline || vim.state().mode == Mode::VisualLine {
146                        display_map.buffer_snapshot.anchor_before(point_range.start)
147                    } else {
148                        display_map.buffer_snapshot.anchor_after(point_range.end)
149                    };
150
151                    if *preserve {
152                        new_selections.push((anchor, line_mode, is_multiline));
153                    }
154                    edits.push((point_range, to_insert));
155                    original_indent_columns.extend(original_indent_column);
156                }
157
158                editor.edit_with_block_indent(edits, original_indent_columns, cx);
159
160                // in line_mode vim will insert the new text on the next (or previous if before) line
161                // and put the cursor on the first non-blank character of the first inserted line (or at the end if the first line is blank).
162                // otherwise vim will insert the next text at (or before) the current cursor position,
163                // the cursor will go to the last (or first, if is_multiline) inserted character.
164                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
165                    s.replace_cursors_with(|map| {
166                        let mut cursors = Vec::new();
167                        for (anchor, line_mode, is_multiline) in &new_selections {
168                            let mut cursor = anchor.to_display_point(map);
169                            if *line_mode {
170                                if !before {
171                                    cursor =
172                                        movement::down(map, cursor, SelectionGoal::None, false).0;
173                                }
174                                cursor = movement::indented_line_beginning(map, cursor, true);
175                            } else if !is_multiline {
176                                cursor = movement::saturating_left(map, cursor)
177                            }
178                            cursors.push(cursor);
179                            if vim.state().mode == Mode::VisualBlock {
180                                break;
181                            }
182                        }
183
184                        cursors
185                    });
186                })
187            });
188        });
189        vim.switch_mode(Mode::Normal, true, cx);
190    });
191}
192
193#[cfg(test)]
194mod test {
195    use crate::{
196        state::Mode,
197        test::{NeovimBackedTestContext, VimTestContext},
198    };
199    use indoc::indoc;
200
201    #[gpui::test]
202    async fn test_paste(cx: &mut gpui::TestAppContext) {
203        let mut cx = NeovimBackedTestContext::new(cx).await;
204
205        // single line
206        cx.set_shared_state(indoc! {"
207            The quick brown
208            fox ˇjumps over
209            the lazy dog"})
210            .await;
211        cx.simulate_shared_keystrokes(["v", "w", "y"]).await;
212        cx.assert_shared_clipboard("jumps o").await;
213        cx.set_shared_state(indoc! {"
214            The quick brown
215            fox jumps oveˇr
216            the lazy dog"})
217            .await;
218        cx.simulate_shared_keystroke("p").await;
219        cx.assert_shared_state(indoc! {"
220            The quick brown
221            fox jumps overjumps ˇo
222            the lazy dog"})
223            .await;
224
225        cx.set_shared_state(indoc! {"
226            The quick brown
227            fox jumps oveˇr
228            the lazy dog"})
229            .await;
230        cx.simulate_shared_keystroke("shift-p").await;
231        cx.assert_shared_state(indoc! {"
232            The quick brown
233            fox jumps ovejumps ˇor
234            the lazy dog"})
235            .await;
236
237        // line mode
238        cx.set_shared_state(indoc! {"
239            The quick brown
240            fox juˇmps over
241            the lazy dog"})
242            .await;
243        cx.simulate_shared_keystrokes(["d", "d"]).await;
244        cx.assert_shared_clipboard("fox jumps over\n").await;
245        cx.assert_shared_state(indoc! {"
246            The quick brown
247            the laˇzy dog"})
248            .await;
249        cx.simulate_shared_keystroke("p").await;
250        cx.assert_shared_state(indoc! {"
251            The quick brown
252            the lazy dog
253            ˇfox jumps over"})
254            .await;
255        cx.simulate_shared_keystrokes(["k", "shift-p"]).await;
256        cx.assert_shared_state(indoc! {"
257            The quick brown
258            ˇfox jumps over
259            the lazy dog
260            fox jumps over"})
261            .await;
262
263        // multiline, cursor to first character of pasted text.
264        cx.set_shared_state(indoc! {"
265            The quick brown
266            fox jumps ˇover
267            the lazy dog"})
268            .await;
269        cx.simulate_shared_keystrokes(["v", "j", "y"]).await;
270        cx.assert_shared_clipboard("over\nthe lazy do").await;
271
272        cx.simulate_shared_keystroke("p").await;
273        cx.assert_shared_state(indoc! {"
274            The quick brown
275            fox jumps oˇover
276            the lazy dover
277            the lazy dog"})
278            .await;
279        cx.simulate_shared_keystrokes(["u", "shift-p"]).await;
280        cx.assert_shared_state(indoc! {"
281            The quick brown
282            fox jumps ˇover
283            the lazy doover
284            the lazy dog"})
285            .await;
286    }
287
288    #[gpui::test]
289    async fn test_paste_visual(cx: &mut gpui::TestAppContext) {
290        let mut cx = NeovimBackedTestContext::new(cx).await;
291
292        // copy in visual mode
293        cx.set_shared_state(indoc! {"
294                The quick brown
295                fox jˇumps over
296                the lazy dog"})
297            .await;
298        cx.simulate_shared_keystrokes(["v", "i", "w", "y"]).await;
299        cx.assert_shared_state(indoc! {"
300                The quick brown
301                fox ˇjumps over
302                the lazy dog"})
303            .await;
304        // paste in visual mode
305        cx.simulate_shared_keystrokes(["w", "v", "i", "w", "p"])
306            .await;
307        cx.assert_shared_state(indoc! {"
308                The quick brown
309                fox jumps jumpˇs
310                the lazy dog"})
311            .await;
312        cx.assert_shared_clipboard("over").await;
313        // paste in visual line mode
314        cx.simulate_shared_keystrokes(["up", "shift-v", "shift-p"])
315            .await;
316        cx.assert_shared_state(indoc! {"
317            ˇover
318            fox jumps jumps
319            the lazy dog"})
320            .await;
321        cx.assert_shared_clipboard("over").await;
322        // paste in visual block mode
323        cx.simulate_shared_keystrokes(["ctrl-v", "down", "down", "p"])
324            .await;
325        cx.assert_shared_state(indoc! {"
326            oveˇrver
327            overox jumps jumps
328            overhe lazy dog"})
329            .await;
330
331        // copy in visual line mode
332        cx.set_shared_state(indoc! {"
333                The quick brown
334                fox juˇmps over
335                the lazy dog"})
336            .await;
337        cx.simulate_shared_keystrokes(["shift-v", "d"]).await;
338        cx.assert_shared_state(indoc! {"
339                The quick brown
340                the laˇzy dog"})
341            .await;
342        // paste in visual mode
343        cx.simulate_shared_keystrokes(["v", "i", "w", "p"]).await;
344        cx.assert_shared_state(
345            &indoc! {"
346                The quick brown
347                the_
348                ˇfox jumps over
349                _dog"}
350            .replace("_", " "), // Hack for trailing whitespace
351        )
352        .await;
353        cx.assert_shared_clipboard("lazy").await;
354        cx.set_shared_state(indoc! {"
355            The quick brown
356            fox juˇmps over
357            the lazy dog"})
358            .await;
359        cx.simulate_shared_keystrokes(["shift-v", "d"]).await;
360        cx.assert_shared_state(indoc! {"
361            The quick brown
362            the laˇzy dog"})
363            .await;
364        // paste in visual line mode
365        cx.simulate_shared_keystrokes(["k", "shift-v", "p"]).await;
366        cx.assert_shared_state(indoc! {"
367            ˇfox jumps over
368            the lazy dog"})
369            .await;
370        cx.assert_shared_clipboard("The quick brown\n").await;
371    }
372
373    #[gpui::test]
374    async fn test_paste_visual_block(cx: &mut gpui::TestAppContext) {
375        let mut cx = NeovimBackedTestContext::new(cx).await;
376        // copy in visual block mode
377        cx.set_shared_state(indoc! {"
378            The ˇquick brown
379            fox jumps over
380            the lazy dog"})
381            .await;
382        cx.simulate_shared_keystrokes(["ctrl-v", "2", "j", "y"])
383            .await;
384        cx.assert_shared_clipboard("q\nj\nl").await;
385        cx.simulate_shared_keystrokes(["p"]).await;
386        cx.assert_shared_state(indoc! {"
387            The qˇquick brown
388            fox jjumps over
389            the llazy dog"})
390            .await;
391        cx.simulate_shared_keystrokes(["v", "i", "w", "shift-p"])
392            .await;
393        cx.assert_shared_state(indoc! {"
394            The ˇq brown
395            fox jjjumps over
396            the lllazy dog"})
397            .await;
398        cx.simulate_shared_keystrokes(["v", "i", "w", "shift-p"])
399            .await;
400
401        cx.set_shared_state(indoc! {"
402            The ˇquick brown
403            fox jumps over
404            the lazy dog"})
405            .await;
406        cx.simulate_shared_keystrokes(["ctrl-v", "j", "y"]).await;
407        cx.assert_shared_clipboard("q\nj").await;
408        cx.simulate_shared_keystrokes(["l", "ctrl-v", "2", "j", "shift-p"])
409            .await;
410        cx.assert_shared_state(indoc! {"
411            The qˇqick brown
412            fox jjmps over
413            the lzy dog"})
414            .await;
415
416        cx.simulate_shared_keystrokes(["shift-v", "p"]).await;
417        cx.assert_shared_state(indoc! {"
418            ˇq
419            j
420            fox jjmps over
421            the lzy dog"})
422            .await;
423    }
424
425    #[gpui::test]
426    async fn test_paste_indent(cx: &mut gpui::TestAppContext) {
427        let mut cx = VimTestContext::new_typescript(cx).await;
428
429        cx.set_state(
430            indoc! {"
431            class A {ˇ
432            }
433        "},
434            Mode::Normal,
435        );
436        cx.simulate_keystrokes(["o", "a", "(", ")", "{", "escape"]);
437        cx.assert_state(
438            indoc! {"
439            class A {
440                a()ˇ{}
441            }
442            "},
443            Mode::Normal,
444        );
445        // cursor goes to the first non-blank character in the line;
446        cx.simulate_keystrokes(["y", "y", "p"]);
447        cx.assert_state(
448            indoc! {"
449            class A {
450                a(){}
451                ˇa(){}
452            }
453            "},
454            Mode::Normal,
455        );
456        // indentation is preserved when pasting
457        cx.simulate_keystrokes(["u", "shift-v", "up", "y", "shift-p"]);
458        cx.assert_state(
459            indoc! {"
460                ˇclass A {
461                    a(){}
462                class A {
463                    a(){}
464                }
465                "},
466            Mode::Normal,
467        );
468    }
469}