utils.rs

 1use editor::{ClipboardSelection, Editor};
 2use gpui::{AppContext, ClipboardItem};
 3use language::Point;
 4
 5pub fn copy_selections_content(editor: &mut Editor, linewise: bool, cx: &mut AppContext) {
 6    let selections = editor.selections.all_adjusted(cx);
 7    let buffer = editor.buffer().read(cx).snapshot(cx);
 8    let mut text = String::new();
 9    let mut clipboard_selections = Vec::with_capacity(selections.len());
10    {
11        let mut is_first = true;
12        for selection in selections.iter() {
13            let mut start = selection.start;
14            let end = selection.end;
15            if is_first {
16                is_first = false;
17            } else {
18                text.push_str("\n");
19            }
20            let initial_len = text.len();
21
22            // if the file does not end with \n, and our line-mode selection ends on
23            // that line, we will have expanded the start of the selection to ensure it
24            // contains a newline (so that delete works as expected). We undo that change
25            // here.
26            let is_last_line = linewise
27                && end.row == buffer.max_buffer_row()
28                && buffer.max_point().column > 0
29                && start.row < buffer.max_buffer_row()
30                && start == Point::new(start.row, buffer.line_len(start.row));
31
32            if is_last_line {
33                start = Point::new(start.row + 1, 0);
34            }
35            for chunk in buffer.text_for_range(start..end) {
36                text.push_str(chunk);
37            }
38            if is_last_line {
39                text.push_str("\n");
40            }
41            clipboard_selections.push(ClipboardSelection {
42                len: text.len() - initial_len,
43                is_entire_line: linewise,
44                first_line_indent: buffer.indent_size_for_line(start.row).len,
45            });
46        }
47    }
48
49    cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
50}