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 == Point::new(start.row, buffer.line_len(start.row));
30
31            if is_last_line {
32                start = Point::new(buffer.max_buffer_row(), 0);
33            }
34            for chunk in buffer.text_for_range(start..end) {
35                text.push_str(chunk);
36            }
37            if is_last_line {
38                text.push_str("\n");
39            }
40            clipboard_selections.push(ClipboardSelection {
41                len: text.len() - initial_len,
42                is_entire_line: linewise,
43                first_line_indent: buffer.indent_size_for_line(start.row).len,
44            });
45        }
46    }
47
48    cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
49}