1pub mod display_map;
2mod element;
3pub mod movement;
4
5#[cfg(test)]
6mod test;
7
8use buffer::*;
9use clock::ReplicaId;
10pub use display_map::DisplayPoint;
11use display_map::*;
12pub use element::*;
13use gpui::{
14 action, color::Color, fonts::TextStyle, geometry::vector::Vector2F, keymap::Binding,
15 text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
16 MutableAppContext, RenderContext, View, ViewContext, WeakViewHandle,
17};
18use serde::{Deserialize, Serialize};
19use smallvec::SmallVec;
20use smol::Timer;
21use std::{
22 cell::RefCell,
23 cmp::{self, Ordering},
24 mem,
25 ops::{Range, RangeInclusive},
26 rc::Rc,
27 sync::Arc,
28 time::Duration,
29};
30use sum_tree::Bias;
31use theme::EditorStyle;
32use util::post_inc;
33
34const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
35const MAX_LINE_LEN: usize = 1024;
36
37action!(Cancel);
38action!(Backspace);
39action!(Delete);
40action!(Insert, String);
41action!(DeleteLine);
42action!(DeleteToPreviousWordBoundary);
43action!(DeleteToNextWordBoundary);
44action!(DeleteToBeginningOfLine);
45action!(DeleteToEndOfLine);
46action!(CutToEndOfLine);
47action!(DuplicateLine);
48action!(MoveLineUp);
49action!(MoveLineDown);
50action!(Cut);
51action!(Copy);
52action!(Paste);
53action!(Undo);
54action!(Redo);
55action!(MoveUp);
56action!(MoveDown);
57action!(MoveLeft);
58action!(MoveRight);
59action!(MoveToPreviousWordBoundary);
60action!(MoveToNextWordBoundary);
61action!(MoveToBeginningOfLine);
62action!(MoveToEndOfLine);
63action!(MoveToBeginning);
64action!(MoveToEnd);
65action!(SelectUp);
66action!(SelectDown);
67action!(SelectLeft);
68action!(SelectRight);
69action!(SelectToPreviousWordBoundary);
70action!(SelectToNextWordBoundary);
71action!(SelectToBeginningOfLine, bool);
72action!(SelectToEndOfLine);
73action!(SelectToBeginning);
74action!(SelectToEnd);
75action!(SelectAll);
76action!(SelectLine);
77action!(SplitSelectionIntoLines);
78action!(AddSelectionAbove);
79action!(AddSelectionBelow);
80action!(SelectLargerSyntaxNode);
81action!(SelectSmallerSyntaxNode);
82action!(MoveToEnclosingBracket);
83action!(PageUp);
84action!(PageDown);
85action!(Fold);
86action!(Unfold);
87action!(FoldSelectedRanges);
88action!(Scroll, Vector2F);
89action!(Select, SelectPhase);
90
91pub fn init(cx: &mut MutableAppContext) {
92 cx.add_bindings(vec![
93 Binding::new("escape", Cancel, Some("Editor")),
94 Binding::new("backspace", Backspace, Some("Editor")),
95 Binding::new("ctrl-h", Backspace, Some("Editor")),
96 Binding::new("delete", Delete, Some("Editor")),
97 Binding::new("ctrl-d", Delete, Some("Editor")),
98 Binding::new("enter", Insert("\n".into()), Some("Editor && mode == full")),
99 Binding::new(
100 "alt-enter",
101 Insert("\n".into()),
102 Some("Editor && mode == auto_height"),
103 ),
104 Binding::new("tab", Insert("\t".into()), Some("Editor")),
105 Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
106 Binding::new(
107 "alt-backspace",
108 DeleteToPreviousWordBoundary,
109 Some("Editor"),
110 ),
111 Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
112 Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
113 Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
114 Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
115 Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
116 Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
117 Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
118 Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
119 Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
120 Binding::new("cmd-x", Cut, Some("Editor")),
121 Binding::new("cmd-c", Copy, Some("Editor")),
122 Binding::new("cmd-v", Paste, Some("Editor")),
123 Binding::new("cmd-z", Undo, Some("Editor")),
124 Binding::new("cmd-shift-Z", Redo, Some("Editor")),
125 Binding::new("up", MoveUp, Some("Editor")),
126 Binding::new("down", MoveDown, Some("Editor")),
127 Binding::new("left", MoveLeft, Some("Editor")),
128 Binding::new("right", MoveRight, Some("Editor")),
129 Binding::new("ctrl-p", MoveUp, Some("Editor")),
130 Binding::new("ctrl-n", MoveDown, Some("Editor")),
131 Binding::new("ctrl-b", MoveLeft, Some("Editor")),
132 Binding::new("ctrl-f", MoveRight, Some("Editor")),
133 Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
134 Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
135 Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
136 Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
137 Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
138 Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
139 Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
140 Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
141 Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
142 Binding::new("cmd-down", MoveToEnd, Some("Editor")),
143 Binding::new("shift-up", SelectUp, Some("Editor")),
144 Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
145 Binding::new("shift-down", SelectDown, Some("Editor")),
146 Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
147 Binding::new("shift-left", SelectLeft, Some("Editor")),
148 Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
149 Binding::new("shift-right", SelectRight, Some("Editor")),
150 Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
151 Binding::new(
152 "alt-shift-left",
153 SelectToPreviousWordBoundary,
154 Some("Editor"),
155 ),
156 Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
157 Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
158 Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
159 Binding::new(
160 "cmd-shift-left",
161 SelectToBeginningOfLine(true),
162 Some("Editor"),
163 ),
164 Binding::new(
165 "ctrl-shift-A",
166 SelectToBeginningOfLine(true),
167 Some("Editor"),
168 ),
169 Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
170 Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
171 Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
172 Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
173 Binding::new("cmd-a", SelectAll, Some("Editor")),
174 Binding::new("cmd-l", SelectLine, Some("Editor")),
175 Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
176 Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
177 Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
178 Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
179 Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
180 Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
181 Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
182 Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
183 Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
184 Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
185 Binding::new("pageup", PageUp, Some("Editor")),
186 Binding::new("pagedown", PageDown, Some("Editor")),
187 Binding::new("alt-cmd-[", Fold, Some("Editor")),
188 Binding::new("alt-cmd-]", Unfold, Some("Editor")),
189 Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
190 ]);
191
192 cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
193 cx.add_action(Editor::select);
194 cx.add_action(Editor::cancel);
195 cx.add_action(Editor::insert);
196 cx.add_action(Editor::backspace);
197 cx.add_action(Editor::delete);
198 cx.add_action(Editor::delete_line);
199 cx.add_action(Editor::delete_to_previous_word_boundary);
200 cx.add_action(Editor::delete_to_next_word_boundary);
201 cx.add_action(Editor::delete_to_beginning_of_line);
202 cx.add_action(Editor::delete_to_end_of_line);
203 cx.add_action(Editor::cut_to_end_of_line);
204 cx.add_action(Editor::duplicate_line);
205 cx.add_action(Editor::move_line_up);
206 cx.add_action(Editor::move_line_down);
207 cx.add_action(Editor::cut);
208 cx.add_action(Editor::copy);
209 cx.add_action(Editor::paste);
210 cx.add_action(Editor::undo);
211 cx.add_action(Editor::redo);
212 cx.add_action(Editor::move_up);
213 cx.add_action(Editor::move_down);
214 cx.add_action(Editor::move_left);
215 cx.add_action(Editor::move_right);
216 cx.add_action(Editor::move_to_previous_word_boundary);
217 cx.add_action(Editor::move_to_next_word_boundary);
218 cx.add_action(Editor::move_to_beginning_of_line);
219 cx.add_action(Editor::move_to_end_of_line);
220 cx.add_action(Editor::move_to_beginning);
221 cx.add_action(Editor::move_to_end);
222 cx.add_action(Editor::select_up);
223 cx.add_action(Editor::select_down);
224 cx.add_action(Editor::select_left);
225 cx.add_action(Editor::select_right);
226 cx.add_action(Editor::select_to_previous_word_boundary);
227 cx.add_action(Editor::select_to_next_word_boundary);
228 cx.add_action(Editor::select_to_beginning_of_line);
229 cx.add_action(Editor::select_to_end_of_line);
230 cx.add_action(Editor::select_to_beginning);
231 cx.add_action(Editor::select_to_end);
232 cx.add_action(Editor::select_all);
233 cx.add_action(Editor::select_line);
234 cx.add_action(Editor::split_selection_into_lines);
235 cx.add_action(Editor::add_selection_above);
236 cx.add_action(Editor::add_selection_below);
237 cx.add_action(Editor::select_larger_syntax_node);
238 cx.add_action(Editor::select_smaller_syntax_node);
239 cx.add_action(Editor::move_to_enclosing_bracket);
240 cx.add_action(Editor::page_up);
241 cx.add_action(Editor::page_down);
242 cx.add_action(Editor::fold);
243 cx.add_action(Editor::unfold);
244 cx.add_action(Editor::fold_selected_ranges);
245}
246
247trait SelectionExt {
248 fn display_range(&self, map: &DisplayMapSnapshot) -> Range<DisplayPoint>;
249 fn spanned_rows(
250 &self,
251 include_end_if_at_line_start: bool,
252 map: &DisplayMapSnapshot,
253 ) -> SpannedRows;
254}
255
256struct SpannedRows {
257 buffer_rows: Range<u32>,
258 display_rows: Range<u32>,
259}
260
261#[derive(Clone, Debug)]
262pub enum SelectPhase {
263 Begin {
264 position: DisplayPoint,
265 add: bool,
266 },
267 Update {
268 position: DisplayPoint,
269 scroll_position: Vector2F,
270 },
271 End,
272}
273
274#[derive(Copy, Clone, PartialEq, Eq)]
275pub enum EditorMode {
276 SingleLine,
277 AutoHeight { max_lines: usize },
278 Full,
279}
280
281#[derive(Clone)]
282pub struct EditorSettings {
283 pub tab_size: usize,
284 pub style: EditorStyle,
285}
286
287pub struct Editor {
288 handle: WeakViewHandle<Self>,
289 buffer: ModelHandle<Buffer>,
290 display_map: ModelHandle<DisplayMap>,
291 selection_set_id: SelectionSetId,
292 pending_selection: Option<Selection>,
293 next_selection_id: usize,
294 add_selections_state: Option<AddSelectionsState>,
295 select_larger_syntax_node_stack: Vec<Arc<[Selection]>>,
296 scroll_position: Vector2F,
297 scroll_top_anchor: Anchor,
298 autoscroll_requested: bool,
299 build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
300 focused: bool,
301 show_local_cursors: bool,
302 blink_epoch: usize,
303 blinking_paused: bool,
304 mode: EditorMode,
305 placeholder_text: Option<Arc<str>>,
306}
307
308pub struct Snapshot {
309 pub mode: EditorMode,
310 pub display_snapshot: DisplayMapSnapshot,
311 pub placeholder_text: Option<Arc<str>>,
312 is_focused: bool,
313 scroll_position: Vector2F,
314 scroll_top_anchor: Anchor,
315}
316
317struct AddSelectionsState {
318 above: bool,
319 stack: Vec<usize>,
320}
321
322#[derive(Serialize, Deserialize)]
323struct ClipboardSelection {
324 len: usize,
325 is_entire_line: bool,
326}
327
328impl Editor {
329 pub fn single_line(
330 build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
331 cx: &mut ViewContext<Self>,
332 ) -> Self {
333 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
334 let mut view = Self::for_buffer(buffer, build_settings, cx);
335 view.mode = EditorMode::SingleLine;
336 view
337 }
338
339 pub fn auto_height(
340 max_lines: usize,
341 build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
342 cx: &mut ViewContext<Self>,
343 ) -> Self {
344 let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
345 let mut view = Self::for_buffer(buffer, build_settings, cx);
346 view.mode = EditorMode::AutoHeight { max_lines };
347 view
348 }
349
350 pub fn for_buffer(
351 buffer: ModelHandle<Buffer>,
352 build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
353 cx: &mut ViewContext<Self>,
354 ) -> Self {
355 Self::new(buffer, Rc::new(RefCell::new(build_settings)), cx)
356 }
357
358 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
359 let mut clone = Self::new(self.buffer.clone(), self.build_settings.clone(), cx);
360 clone.scroll_position = self.scroll_position;
361 clone.scroll_top_anchor = self.scroll_top_anchor.clone();
362 clone
363 }
364
365 pub fn new(
366 buffer: ModelHandle<Buffer>,
367 build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
368 cx: &mut ViewContext<Self>,
369 ) -> Self {
370 let settings = build_settings.borrow_mut()(cx);
371 let display_map = cx.add_model(|cx| {
372 DisplayMap::new(
373 buffer.clone(),
374 settings.tab_size,
375 settings.style.text.font_id,
376 settings.style.text.font_size,
377 None,
378 cx,
379 )
380 });
381 cx.observe(&buffer, Self::on_buffer_changed).detach();
382 cx.subscribe(&buffer, Self::on_buffer_event).detach();
383 cx.observe(&display_map, Self::on_display_map_changed)
384 .detach();
385
386 let mut next_selection_id = 0;
387 let selection_set_id = buffer.update(cx, |buffer, cx| {
388 buffer.add_selection_set(
389 vec![Selection {
390 id: post_inc(&mut next_selection_id),
391 start: buffer.anchor_before(0),
392 end: buffer.anchor_before(0),
393 reversed: false,
394 goal: SelectionGoal::None,
395 }],
396 cx,
397 )
398 });
399 Self {
400 handle: cx.handle().downgrade(),
401 buffer,
402 display_map,
403 selection_set_id,
404 pending_selection: None,
405 next_selection_id,
406 add_selections_state: None,
407 select_larger_syntax_node_stack: Vec::new(),
408 build_settings,
409 scroll_position: Vector2F::zero(),
410 scroll_top_anchor: Anchor::min(),
411 autoscroll_requested: false,
412 focused: false,
413 show_local_cursors: false,
414 blink_epoch: 0,
415 blinking_paused: false,
416 mode: EditorMode::Full,
417 placeholder_text: None,
418 }
419 }
420
421 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
422 self.buffer.read(cx).replica_id()
423 }
424
425 pub fn buffer(&self) -> &ModelHandle<Buffer> {
426 &self.buffer
427 }
428
429 pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> Snapshot {
430 Snapshot {
431 mode: self.mode,
432 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
433 scroll_position: self.scroll_position,
434 scroll_top_anchor: self.scroll_top_anchor.clone(),
435 placeholder_text: self.placeholder_text.clone(),
436 is_focused: self
437 .handle
438 .upgrade(cx)
439 .map_or(false, |handle| handle.is_focused(cx)),
440 }
441 }
442
443 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
444 self.buffer.read(cx).language()
445 }
446
447 pub fn set_placeholder_text(
448 &mut self,
449 placeholder_text: impl Into<Arc<str>>,
450 cx: &mut ViewContext<Self>,
451 ) {
452 self.placeholder_text = Some(placeholder_text.into());
453 cx.notify();
454 }
455
456 fn set_scroll_position(&mut self, mut scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
457 let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
458 let scroll_top_buffer_offset =
459 DisplayPoint::new(scroll_position.y() as u32, 0).to_buffer_offset(&map, Bias::Right);
460 self.scroll_top_anchor = self
461 .buffer
462 .read(cx)
463 .anchor_at(scroll_top_buffer_offset, Bias::Right);
464 scroll_position.set_y(scroll_position.y().fract());
465 self.scroll_position = scroll_position;
466 cx.notify();
467 }
468
469 pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
470 if max < self.scroll_position.x() {
471 self.scroll_position.set_x(max);
472 true
473 } else {
474 false
475 }
476 }
477
478 pub fn autoscroll_vertically(
479 &mut self,
480 viewport_height: f32,
481 line_height: f32,
482 cx: &mut ViewContext<Self>,
483 ) -> bool {
484 let visible_lines = viewport_height / line_height;
485 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
486 let mut scroll_position =
487 compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
488 let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
489 (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
490 } else {
491 display_map.max_point().row().saturating_sub(1) as f32
492 };
493 if scroll_position.y() > max_scroll_top {
494 scroll_position.set_y(max_scroll_top);
495 self.set_scroll_position(scroll_position, cx);
496 }
497
498 if self.autoscroll_requested {
499 self.autoscroll_requested = false;
500 } else {
501 return false;
502 }
503
504 let selections = self.selections(cx);
505 let first_cursor_top = selections
506 .first()
507 .unwrap()
508 .head()
509 .to_display_point(&display_map, Bias::Left)
510 .row() as f32;
511 let last_cursor_bottom = selections
512 .last()
513 .unwrap()
514 .head()
515 .to_display_point(&display_map, Bias::Right)
516 .row() as f32
517 + 1.0;
518
519 let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
520 0.
521 } else {
522 ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0)
523 .floor()
524 .min(3.0)
525 };
526 if margin < 0.0 {
527 return false;
528 }
529
530 let target_top = (first_cursor_top - margin).max(0.0);
531 let target_bottom = last_cursor_bottom + margin;
532 let start_row = scroll_position.y();
533 let end_row = start_row + visible_lines;
534
535 if target_top < start_row {
536 scroll_position.set_y(target_top);
537 self.set_scroll_position(scroll_position, cx);
538 } else if target_bottom >= end_row {
539 scroll_position.set_y(target_bottom - visible_lines);
540 self.set_scroll_position(scroll_position, cx);
541 }
542
543 true
544 }
545
546 pub fn autoscroll_horizontally(
547 &mut self,
548 start_row: u32,
549 viewport_width: f32,
550 scroll_width: f32,
551 max_glyph_width: f32,
552 layouts: &[text_layout::Line],
553 cx: &mut ViewContext<Self>,
554 ) -> bool {
555 let selections = self.selections(cx);
556 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
557 let mut target_left = std::f32::INFINITY;
558 let mut target_right = 0.0_f32;
559 for selection in selections.iter() {
560 let head = selection.head().to_display_point(&display_map, Bias::Left);
561 let start_column = head.column().saturating_sub(3);
562 let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
563 target_left = target_left
564 .min(layouts[(head.row() - start_row) as usize].x_for_index(start_column as usize));
565 target_right = target_right.max(
566 layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
567 + max_glyph_width,
568 );
569 }
570 target_right = target_right.min(scroll_width);
571
572 if target_right - target_left > viewport_width {
573 return false;
574 }
575
576 let scroll_left = self.scroll_position.x() * max_glyph_width;
577 let scroll_right = scroll_left + viewport_width;
578
579 if target_left < scroll_left {
580 self.scroll_position.set_x(target_left / max_glyph_width);
581 true
582 } else if target_right > scroll_right {
583 self.scroll_position
584 .set_x((target_right - viewport_width) / max_glyph_width);
585 true
586 } else {
587 false
588 }
589 }
590
591 fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
592 match phase {
593 SelectPhase::Begin { position, add } => self.begin_selection(*position, *add, cx),
594 SelectPhase::Update {
595 position,
596 scroll_position,
597 } => self.update_selection(*position, *scroll_position, cx),
598 SelectPhase::End => self.end_selection(cx),
599 }
600 }
601
602 fn begin_selection(&mut self, position: DisplayPoint, add: bool, cx: &mut ViewContext<Self>) {
603 if !self.focused {
604 cx.focus_self();
605 cx.emit(Event::Activate);
606 }
607
608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
609 let cursor = display_map.anchor_before(position, Bias::Left);
610 let selection = Selection {
611 id: post_inc(&mut self.next_selection_id),
612 start: cursor.clone(),
613 end: cursor,
614 reversed: false,
615 goal: SelectionGoal::None,
616 };
617
618 if !add {
619 self.update_selections(Vec::new(), false, cx);
620 }
621 self.pending_selection = Some(selection);
622
623 cx.notify();
624 }
625
626 fn update_selection(
627 &mut self,
628 position: DisplayPoint,
629 scroll_position: Vector2F,
630 cx: &mut ViewContext<Self>,
631 ) {
632 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
633 let buffer = self.buffer.read(cx);
634 let cursor = display_map.anchor_before(position, Bias::Left);
635 if let Some(selection) = self.pending_selection.as_mut() {
636 selection.set_head(buffer, cursor);
637 } else {
638 log::error!("update_selection dispatched with no pending selection");
639 return;
640 }
641
642 self.set_scroll_position(scroll_position, cx);
643 cx.notify();
644 }
645
646 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
647 if let Some(selection) = self.pending_selection.take() {
648 let mut selections = self.selections(cx).to_vec();
649 let ix = self.selection_insertion_index(&selections, &selection.start, cx.as_ref());
650 selections.insert(ix, selection);
651 self.update_selections(selections, false, cx);
652 }
653 }
654
655 pub fn is_selecting(&self) -> bool {
656 self.pending_selection.is_some()
657 }
658
659 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
660 if let Some(pending_selection) = self.pending_selection.take() {
661 let selections = self.selections(cx);
662 if selections.is_empty() {
663 self.update_selections(vec![pending_selection], true, cx);
664 }
665 } else {
666 let selections = self.selections(cx);
667 let mut oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
668 if selections.len() == 1 {
669 oldest_selection.start = oldest_selection.head().clone();
670 oldest_selection.end = oldest_selection.head().clone();
671 }
672 self.update_selections(vec![oldest_selection], true, cx);
673 }
674 }
675
676 fn select_ranges<I, T>(&mut self, ranges: I, autoscroll: bool, cx: &mut ViewContext<Self>)
677 where
678 I: IntoIterator<Item = Range<T>>,
679 T: ToOffset,
680 {
681 let buffer = self.buffer.read(cx);
682 let mut selections = Vec::new();
683 for range in ranges {
684 let mut start = range.start.to_offset(buffer);
685 let mut end = range.end.to_offset(buffer);
686 let reversed = if start > end {
687 mem::swap(&mut start, &mut end);
688 true
689 } else {
690 false
691 };
692 selections.push(Selection {
693 id: post_inc(&mut self.next_selection_id),
694 start: buffer.anchor_before(start),
695 end: buffer.anchor_before(end),
696 reversed,
697 goal: SelectionGoal::None,
698 });
699 }
700 self.update_selections(selections, autoscroll, cx);
701 }
702
703 #[cfg(test)]
704 fn select_display_ranges<'a, T>(
705 &mut self,
706 ranges: T,
707 cx: &mut ViewContext<Self>,
708 ) -> anyhow::Result<()>
709 where
710 T: IntoIterator<Item = &'a Range<DisplayPoint>>,
711 {
712 let mut selections = Vec::new();
713 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
714 for range in ranges {
715 let mut start = range.start;
716 let mut end = range.end;
717 let reversed = if start > end {
718 mem::swap(&mut start, &mut end);
719 true
720 } else {
721 false
722 };
723
724 selections.push(Selection {
725 id: post_inc(&mut self.next_selection_id),
726 start: display_map.anchor_before(start, Bias::Left),
727 end: display_map.anchor_before(end, Bias::Left),
728 reversed,
729 goal: SelectionGoal::None,
730 });
731 }
732 self.update_selections(selections, false, cx);
733 Ok(())
734 }
735
736 pub fn insert(&mut self, action: &Insert, cx: &mut ViewContext<Self>) {
737 let mut old_selections = SmallVec::<[_; 32]>::new();
738 {
739 let selections = self.selections(cx);
740 let buffer = self.buffer.read(cx);
741 for selection in selections.iter() {
742 let start = selection.start.to_offset(buffer);
743 let end = selection.end.to_offset(buffer);
744 old_selections.push((selection.id, start..end));
745 }
746 }
747
748 self.start_transaction(cx);
749 let mut new_selections = Vec::new();
750 self.buffer.update(cx, |buffer, cx| {
751 let edit_ranges = old_selections.iter().map(|(_, range)| range.clone());
752 buffer.edit(edit_ranges, action.0.as_str(), cx);
753 let text_len = action.0.len() as isize;
754 let mut delta = 0_isize;
755 new_selections = old_selections
756 .into_iter()
757 .map(|(id, range)| {
758 let start = range.start as isize;
759 let end = range.end as isize;
760 let anchor = buffer.anchor_before((start + delta + text_len) as usize);
761 let deleted_count = end - start;
762 delta += text_len - deleted_count;
763 Selection {
764 id,
765 start: anchor.clone(),
766 end: anchor,
767 reversed: false,
768 goal: SelectionGoal::None,
769 }
770 })
771 .collect();
772 });
773
774 self.update_selections(new_selections, true, cx);
775 self.autoclose_pairs(cx);
776 self.end_transaction(cx);
777 }
778
779 fn autoclose_pairs(&mut self, cx: &mut ViewContext<Self>) {
780 let selections = self.selections(cx);
781 self.buffer.update(cx, |buffer, cx| {
782 let autoclose_pair = buffer.language().and_then(|language| {
783 let first_selection_start = selections.first().unwrap().start.to_offset(&*buffer);
784 let pair = language.autoclose_pairs().iter().find(|pair| {
785 buffer.contains_str_at(
786 first_selection_start.saturating_sub(pair.start.len()),
787 &pair.start,
788 )
789 });
790 pair.and_then(|pair| {
791 let should_autoclose = selections[1..].iter().all(|selection| {
792 let selection_start = selection.start.to_offset(&*buffer);
793 buffer.contains_str_at(
794 selection_start.saturating_sub(pair.start.len()),
795 &pair.start,
796 )
797 });
798
799 if should_autoclose {
800 Some(pair.clone())
801 } else {
802 None
803 }
804 })
805 });
806
807 if let Some(pair) = autoclose_pair {
808 let mut selection_ranges = SmallVec::<[_; 32]>::new();
809 for selection in selections.as_ref() {
810 let start = selection.start.to_offset(&*buffer);
811 let end = selection.end.to_offset(&*buffer);
812 selection_ranges.push(start..end);
813 }
814
815 buffer.edit(selection_ranges, &pair.end, cx);
816 }
817 });
818 }
819
820 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
821 self.start_transaction(cx);
822 self.select_all(&SelectAll, cx);
823 self.insert(&Insert(String::new()), cx);
824 self.end_transaction(cx);
825 }
826
827 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
828 self.start_transaction(cx);
829 let mut selections = self.selections(cx).to_vec();
830 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
831 {
832 let buffer = self.buffer.read(cx);
833 for selection in &mut selections {
834 let range = selection.point_range(buffer);
835 if range.start == range.end {
836 let head = selection.head().to_display_point(&display_map, Bias::Left);
837 let cursor = display_map
838 .anchor_before(movement::left(&display_map, head).unwrap(), Bias::Left);
839 selection.set_head(&buffer, cursor);
840 selection.goal = SelectionGoal::None;
841 }
842 }
843 }
844
845 self.update_selections(selections, true, cx);
846 self.insert(&Insert(String::new()), cx);
847 self.end_transaction(cx);
848 }
849
850 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
851 self.start_transaction(cx);
852 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
853 let mut selections = self.selections(cx).to_vec();
854 {
855 let buffer = self.buffer.read(cx);
856 for selection in &mut selections {
857 let range = selection.point_range(buffer);
858 if range.start == range.end {
859 let head = selection.head().to_display_point(&display_map, Bias::Left);
860 let cursor = display_map
861 .anchor_before(movement::right(&display_map, head).unwrap(), Bias::Right);
862 selection.set_head(&buffer, cursor);
863 selection.goal = SelectionGoal::None;
864 }
865 }
866 }
867
868 self.update_selections(selections, true, cx);
869 self.insert(&Insert(String::new()), cx);
870 self.end_transaction(cx);
871 }
872
873 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
874 self.start_transaction(cx);
875
876 let selections = self.selections(cx);
877 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
878 let buffer = self.buffer.read(cx);
879
880 let mut new_cursors = Vec::new();
881 let mut edit_ranges = Vec::new();
882
883 let mut selections = selections.iter().peekable();
884 while let Some(selection) = selections.next() {
885 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
886 let goal_display_column = selection
887 .head()
888 .to_display_point(&display_map, Bias::Left)
889 .column();
890
891 // Accumulate contiguous regions of rows that we want to delete.
892 while let Some(next_selection) = selections.peek() {
893 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
894 if next_rows.start <= rows.end {
895 rows.end = next_rows.end;
896 selections.next().unwrap();
897 } else {
898 break;
899 }
900 }
901
902 let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
903 let edit_end;
904 let cursor_buffer_row;
905 if buffer.max_point().row >= rows.end {
906 // If there's a line after the range, delete the \n from the end of the row range
907 // and position the cursor on the next line.
908 edit_end = Point::new(rows.end, 0).to_offset(buffer);
909 cursor_buffer_row = rows.end;
910 } else {
911 // If there isn't a line after the range, delete the \n from the line before the
912 // start of the row range and position the cursor there.
913 edit_start = edit_start.saturating_sub(1);
914 edit_end = buffer.len();
915 cursor_buffer_row = rows.start.saturating_sub(1);
916 }
917
918 let mut cursor =
919 Point::new(cursor_buffer_row, 0).to_display_point(&display_map, Bias::Left);
920 *cursor.column_mut() =
921 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
922
923 new_cursors.push((
924 selection.id,
925 cursor.to_buffer_point(&display_map, Bias::Left),
926 ));
927 edit_ranges.push(edit_start..edit_end);
928 }
929
930 new_cursors.sort_unstable_by_key(|(_, range)| range.clone());
931 let new_selections = new_cursors
932 .into_iter()
933 .map(|(id, cursor)| {
934 let anchor = buffer.anchor_before(cursor);
935 Selection {
936 id,
937 start: anchor.clone(),
938 end: anchor,
939 reversed: false,
940 goal: SelectionGoal::None,
941 }
942 })
943 .collect();
944 self.buffer
945 .update(cx, |buffer, cx| buffer.edit(edit_ranges, "", cx));
946 self.update_selections(new_selections, true, cx);
947 self.end_transaction(cx);
948 }
949
950 pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
951 self.start_transaction(cx);
952
953 let mut selections = self.selections(cx).to_vec();
954 {
955 // Temporarily bias selections right to allow newly duplicate lines to push them down
956 // when the selections are at the beginning of a line.
957 let buffer = self.buffer.read(cx);
958 for selection in &mut selections {
959 selection.start = selection.start.bias_right(buffer);
960 selection.end = selection.end.bias_right(buffer);
961 }
962 }
963 self.update_selections(selections.clone(), false, cx);
964
965 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
966 let buffer = self.buffer.read(cx);
967
968 let mut edits = Vec::new();
969 let mut selections_iter = selections.iter_mut().peekable();
970 while let Some(selection) = selections_iter.next() {
971 // Avoid duplicating the same lines twice.
972 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
973 while let Some(next_selection) = selections_iter.peek() {
974 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
975 if next_rows.start <= rows.end - 1 {
976 rows.end = next_rows.end;
977 selections_iter.next().unwrap();
978 } else {
979 break;
980 }
981 }
982
983 // Copy the text from the selected row region and splice it at the start of the region.
984 let start = Point::new(rows.start, 0);
985 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
986 let text = buffer
987 .text_for_range(start..end)
988 .chain(Some("\n"))
989 .collect::<String>();
990 edits.push((start, text));
991 }
992
993 self.buffer.update(cx, |buffer, cx| {
994 for (offset, text) in edits.into_iter().rev() {
995 buffer.edit(Some(offset..offset), text, cx);
996 }
997 });
998
999 // Restore bias on selections.
1000 let buffer = self.buffer.read(cx);
1001 for selection in &mut selections {
1002 selection.start = selection.start.bias_left(buffer);
1003 selection.end = selection.end.bias_left(buffer);
1004 }
1005 self.update_selections(selections, true, cx);
1006
1007 self.end_transaction(cx);
1008 }
1009
1010 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
1011 self.start_transaction(cx);
1012
1013 let selections = self.selections(cx);
1014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1015 let buffer = self.buffer.read(cx);
1016
1017 let mut edits = Vec::new();
1018 let mut new_selection_ranges = Vec::new();
1019 let mut old_folds = Vec::new();
1020 let mut new_folds = Vec::new();
1021
1022 let mut selections = selections.iter().peekable();
1023 let mut contiguous_selections = Vec::new();
1024 while let Some(selection) = selections.next() {
1025 // Accumulate contiguous regions of rows that we want to move.
1026 contiguous_selections.push(selection.point_range(buffer));
1027 let SpannedRows {
1028 mut buffer_rows,
1029 mut display_rows,
1030 } = selection.spanned_rows(false, &display_map);
1031
1032 while let Some(next_selection) = selections.peek() {
1033 let SpannedRows {
1034 buffer_rows: next_buffer_rows,
1035 display_rows: next_display_rows,
1036 } = next_selection.spanned_rows(false, &display_map);
1037 if next_buffer_rows.start <= buffer_rows.end {
1038 buffer_rows.end = next_buffer_rows.end;
1039 display_rows.end = next_display_rows.end;
1040 contiguous_selections.push(next_selection.point_range(buffer));
1041 selections.next().unwrap();
1042 } else {
1043 break;
1044 }
1045 }
1046
1047 // Cut the text from the selected rows and paste it at the start of the previous line.
1048 if display_rows.start != 0 {
1049 let start = Point::new(buffer_rows.start, 0).to_offset(buffer);
1050 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1051 .to_offset(buffer);
1052
1053 let prev_row_display_start = DisplayPoint::new(display_rows.start - 1, 0);
1054 let prev_row_buffer_start = display_map.prev_row_boundary(prev_row_display_start).1;
1055 let prev_row_buffer_start_offset = prev_row_buffer_start.to_offset(buffer);
1056
1057 let mut text = String::new();
1058 text.extend(buffer.text_for_range(start..end));
1059 text.push('\n');
1060 edits.push((
1061 prev_row_buffer_start_offset..prev_row_buffer_start_offset,
1062 text,
1063 ));
1064 edits.push((start - 1..end, String::new()));
1065
1066 let row_delta = buffer_rows.start - prev_row_buffer_start.row;
1067
1068 // Move selections up.
1069 for range in &mut contiguous_selections {
1070 range.start.row -= row_delta;
1071 range.end.row -= row_delta;
1072 }
1073
1074 // Move folds up.
1075 old_folds.push(start..end);
1076 for fold in display_map.folds_in_range(start..end) {
1077 let mut start = fold.start.to_point(buffer);
1078 let mut end = fold.end.to_point(buffer);
1079 start.row -= row_delta;
1080 end.row -= row_delta;
1081 new_folds.push(start..end);
1082 }
1083 }
1084
1085 new_selection_ranges.extend(contiguous_selections.drain(..));
1086 }
1087
1088 self.unfold_ranges(old_folds, cx);
1089 self.buffer.update(cx, |buffer, cx| {
1090 for (range, text) in edits.into_iter().rev() {
1091 buffer.edit(Some(range), text, cx);
1092 }
1093 });
1094 self.fold_ranges(new_folds, cx);
1095 self.select_ranges(new_selection_ranges, true, cx);
1096
1097 self.end_transaction(cx);
1098 }
1099
1100 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1101 self.start_transaction(cx);
1102
1103 let selections = self.selections(cx);
1104 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1105 let buffer = self.buffer.read(cx);
1106
1107 let mut edits = Vec::new();
1108 let mut new_selection_ranges = Vec::new();
1109 let mut old_folds = Vec::new();
1110 let mut new_folds = Vec::new();
1111
1112 let mut selections = selections.iter().peekable();
1113 let mut contiguous_selections = Vec::new();
1114 while let Some(selection) = selections.next() {
1115 // Accumulate contiguous regions of rows that we want to move.
1116 contiguous_selections.push(selection.point_range(buffer));
1117 let SpannedRows {
1118 mut buffer_rows,
1119 mut display_rows,
1120 } = selection.spanned_rows(false, &display_map);
1121 while let Some(next_selection) = selections.peek() {
1122 let SpannedRows {
1123 buffer_rows: next_buffer_rows,
1124 display_rows: next_display_rows,
1125 } = next_selection.spanned_rows(false, &display_map);
1126 if next_buffer_rows.start <= buffer_rows.end {
1127 buffer_rows.end = next_buffer_rows.end;
1128 display_rows.end = next_display_rows.end;
1129 contiguous_selections.push(next_selection.point_range(buffer));
1130 selections.next().unwrap();
1131 } else {
1132 break;
1133 }
1134 }
1135
1136 // Cut the text from the selected rows and paste it at the end of the next line.
1137 if display_rows.end <= display_map.max_point().row() {
1138 let start = Point::new(buffer_rows.start, 0).to_offset(buffer);
1139 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1140 .to_offset(buffer);
1141
1142 let next_row_display_end =
1143 DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1144 let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1145 let next_row_buffer_end_offset = next_row_buffer_end.to_offset(buffer);
1146
1147 let mut text = String::new();
1148 text.push('\n');
1149 text.extend(buffer.text_for_range(start..end));
1150 edits.push((start..end + 1, String::new()));
1151 edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1152
1153 let row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1154
1155 // Move selections down.
1156 for range in &mut contiguous_selections {
1157 range.start.row += row_delta;
1158 range.end.row += row_delta;
1159 }
1160
1161 // Move folds down.
1162 old_folds.push(start..end);
1163 for fold in display_map.folds_in_range(start..end) {
1164 let mut start = fold.start.to_point(buffer);
1165 let mut end = fold.end.to_point(buffer);
1166 start.row += row_delta;
1167 end.row += row_delta;
1168 new_folds.push(start..end);
1169 }
1170 }
1171
1172 new_selection_ranges.extend(contiguous_selections.drain(..));
1173 }
1174
1175 self.unfold_ranges(old_folds, cx);
1176 self.buffer.update(cx, |buffer, cx| {
1177 for (range, text) in edits.into_iter().rev() {
1178 buffer.edit(Some(range), text, cx);
1179 }
1180 });
1181 self.fold_ranges(new_folds, cx);
1182 self.select_ranges(new_selection_ranges, true, cx);
1183
1184 self.end_transaction(cx);
1185 }
1186
1187 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1188 self.start_transaction(cx);
1189 let mut text = String::new();
1190 let mut selections = self.selections(cx).to_vec();
1191 let mut clipboard_selections = Vec::with_capacity(selections.len());
1192 {
1193 let buffer = self.buffer.read(cx);
1194 let max_point = buffer.max_point();
1195 for selection in &mut selections {
1196 let mut start = selection.start.to_point(buffer);
1197 let mut end = selection.end.to_point(buffer);
1198 let is_entire_line = start == end;
1199 if is_entire_line {
1200 start = Point::new(start.row, 0);
1201 end = cmp::min(max_point, Point::new(start.row + 1, 0));
1202 selection.start = buffer.anchor_before(start);
1203 selection.end = buffer.anchor_before(end);
1204 }
1205 let mut len = 0;
1206 for chunk in buffer.text_for_range(start..end) {
1207 text.push_str(chunk);
1208 len += chunk.len();
1209 }
1210 clipboard_selections.push(ClipboardSelection {
1211 len,
1212 is_entire_line,
1213 });
1214 }
1215 }
1216 self.update_selections(selections, true, cx);
1217 self.insert(&Insert(String::new()), cx);
1218 self.end_transaction(cx);
1219
1220 cx.as_mut()
1221 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1222 }
1223
1224 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1225 let selections = self.selections(cx);
1226 let buffer = self.buffer.read(cx);
1227 let max_point = buffer.max_point();
1228 let mut text = String::new();
1229 let mut clipboard_selections = Vec::with_capacity(selections.len());
1230 for selection in selections.iter() {
1231 let mut start = selection.start.to_point(buffer);
1232 let mut end = selection.end.to_point(buffer);
1233 let is_entire_line = start == end;
1234 if is_entire_line {
1235 start = Point::new(start.row, 0);
1236 end = cmp::min(max_point, Point::new(start.row + 1, 0));
1237 }
1238 let mut len = 0;
1239 for chunk in buffer.text_for_range(start..end) {
1240 text.push_str(chunk);
1241 len += chunk.len();
1242 }
1243 clipboard_selections.push(ClipboardSelection {
1244 len,
1245 is_entire_line,
1246 });
1247 }
1248
1249 cx.as_mut()
1250 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1251 }
1252
1253 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1254 if let Some(item) = cx.as_mut().read_from_clipboard() {
1255 let clipboard_text = item.text();
1256 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1257 let selections = self.selections(cx);
1258 let all_selections_were_entire_line =
1259 clipboard_selections.iter().all(|s| s.is_entire_line);
1260 if clipboard_selections.len() != selections.len() {
1261 clipboard_selections.clear();
1262 }
1263
1264 self.start_transaction(cx);
1265 let mut start_offset = 0;
1266 let mut new_selections = Vec::with_capacity(selections.len());
1267 for (i, selection) in selections.iter().enumerate() {
1268 let to_insert;
1269 let entire_line;
1270 if let Some(clipboard_selection) = clipboard_selections.get(i) {
1271 let end_offset = start_offset + clipboard_selection.len;
1272 to_insert = &clipboard_text[start_offset..end_offset];
1273 entire_line = clipboard_selection.is_entire_line;
1274 start_offset = end_offset
1275 } else {
1276 to_insert = clipboard_text.as_str();
1277 entire_line = all_selections_were_entire_line;
1278 }
1279
1280 self.buffer.update(cx, |buffer, cx| {
1281 let selection_start = selection.start.to_point(&*buffer);
1282 let selection_end = selection.end.to_point(&*buffer);
1283
1284 // If the corresponding selection was empty when this slice of the
1285 // clipboard text was written, then the entire line containing the
1286 // selection was copied. If this selection is also currently empty,
1287 // then paste the line before the current line of the buffer.
1288 let new_selection_start = selection.end.bias_right(buffer);
1289 if selection_start == selection_end && entire_line {
1290 let line_start = Point::new(selection_start.row, 0);
1291 buffer.edit(Some(line_start..line_start), to_insert, cx);
1292 } else {
1293 buffer.edit(Some(&selection.start..&selection.end), to_insert, cx);
1294 };
1295
1296 let new_selection_start = new_selection_start.bias_left(buffer);
1297 new_selections.push(Selection {
1298 id: selection.id,
1299 start: new_selection_start.clone(),
1300 end: new_selection_start,
1301 reversed: false,
1302 goal: SelectionGoal::None,
1303 });
1304 });
1305 }
1306 self.update_selections(new_selections, true, cx);
1307 self.end_transaction(cx);
1308 } else {
1309 self.insert(&Insert(clipboard_text.into()), cx);
1310 }
1311 }
1312 }
1313
1314 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1315 self.buffer.update(cx, |buffer, cx| buffer.undo(cx));
1316 }
1317
1318 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
1319 self.buffer.update(cx, |buffer, cx| buffer.redo(cx));
1320 }
1321
1322 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
1323 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1324 let mut selections = self.selections(cx).to_vec();
1325 {
1326 for selection in &mut selections {
1327 let start = selection.start.to_display_point(&display_map, Bias::Left);
1328 let end = selection.end.to_display_point(&display_map, Bias::Left);
1329
1330 if start != end {
1331 selection.end = selection.start.clone();
1332 } else {
1333 let cursor = display_map
1334 .anchor_before(movement::left(&display_map, start).unwrap(), Bias::Left);
1335 selection.start = cursor.clone();
1336 selection.end = cursor;
1337 }
1338 selection.reversed = false;
1339 selection.goal = SelectionGoal::None;
1340 }
1341 }
1342 self.update_selections(selections, true, cx);
1343 }
1344
1345 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
1346 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1347 let mut selections = self.selections(cx).to_vec();
1348 {
1349 let buffer = self.buffer.read(cx);
1350 for selection in &mut selections {
1351 let head = selection.head().to_display_point(&display_map, Bias::Left);
1352 let cursor = display_map
1353 .anchor_before(movement::left(&display_map, head).unwrap(), Bias::Left);
1354 selection.set_head(&buffer, cursor);
1355 selection.goal = SelectionGoal::None;
1356 }
1357 }
1358 self.update_selections(selections, true, cx);
1359 }
1360
1361 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
1362 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1363 let mut selections = self.selections(cx).to_vec();
1364 {
1365 for selection in &mut selections {
1366 let start = selection.start.to_display_point(&display_map, Bias::Left);
1367 let end = selection.end.to_display_point(&display_map, Bias::Left);
1368
1369 if start != end {
1370 selection.start = selection.end.clone();
1371 } else {
1372 let cursor = display_map
1373 .anchor_before(movement::right(&display_map, end).unwrap(), Bias::Right);
1374 selection.start = cursor.clone();
1375 selection.end = cursor;
1376 }
1377 selection.reversed = false;
1378 selection.goal = SelectionGoal::None;
1379 }
1380 }
1381 self.update_selections(selections, true, cx);
1382 }
1383
1384 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
1385 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1386 let mut selections = self.selections(cx).to_vec();
1387 {
1388 let app = cx.as_ref();
1389 let buffer = self.buffer.read(app);
1390 for selection in &mut selections {
1391 let head = selection.head().to_display_point(&display_map, Bias::Left);
1392 let cursor = display_map
1393 .anchor_before(movement::right(&display_map, head).unwrap(), Bias::Right);
1394 selection.set_head(&buffer, cursor);
1395 selection.goal = SelectionGoal::None;
1396 }
1397 }
1398 self.update_selections(selections, true, cx);
1399 }
1400
1401 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
1402 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1403 if matches!(self.mode, EditorMode::SingleLine) {
1404 cx.propagate_action();
1405 } else {
1406 let mut selections = self.selections(cx).to_vec();
1407 {
1408 for selection in &mut selections {
1409 let start = selection.start.to_display_point(&display_map, Bias::Left);
1410 let end = selection.end.to_display_point(&display_map, Bias::Left);
1411 if start != end {
1412 selection.goal = SelectionGoal::None;
1413 }
1414
1415 let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
1416 let cursor = display_map.anchor_before(start, Bias::Left);
1417 selection.start = cursor.clone();
1418 selection.end = cursor;
1419 selection.goal = goal;
1420 selection.reversed = false;
1421 }
1422 }
1423 self.update_selections(selections, true, cx);
1424 }
1425 }
1426
1427 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
1428 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1429 let mut selections = self.selections(cx).to_vec();
1430 {
1431 let app = cx.as_ref();
1432 let buffer = self.buffer.read(app);
1433 for selection in &mut selections {
1434 let head = selection.head().to_display_point(&display_map, Bias::Left);
1435 let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
1436 selection.set_head(&buffer, display_map.anchor_before(head, Bias::Left));
1437 selection.goal = goal;
1438 }
1439 }
1440 self.update_selections(selections, true, cx);
1441 }
1442
1443 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
1444 if matches!(self.mode, EditorMode::SingleLine) {
1445 cx.propagate_action();
1446 } else {
1447 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1448 let mut selections = self.selections(cx).to_vec();
1449 {
1450 for selection in &mut selections {
1451 let start = selection.start.to_display_point(&display_map, Bias::Left);
1452 let end = selection.end.to_display_point(&display_map, Bias::Left);
1453 if start != end {
1454 selection.goal = SelectionGoal::None;
1455 }
1456
1457 let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
1458 let cursor = display_map.anchor_before(start, Bias::Right);
1459 selection.start = cursor.clone();
1460 selection.end = cursor;
1461 selection.goal = goal;
1462 selection.reversed = false;
1463 }
1464 }
1465 self.update_selections(selections, true, cx);
1466 }
1467 }
1468
1469 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
1470 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1471 let mut selections = self.selections(cx).to_vec();
1472 {
1473 let app = cx.as_ref();
1474 let buffer = self.buffer.read(app);
1475 for selection in &mut selections {
1476 let head = selection.head().to_display_point(&display_map, Bias::Left);
1477 let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
1478 selection.set_head(&buffer, display_map.anchor_before(head, Bias::Right));
1479 selection.goal = goal;
1480 }
1481 }
1482 self.update_selections(selections, true, cx);
1483 }
1484
1485 pub fn move_to_previous_word_boundary(
1486 &mut self,
1487 _: &MoveToPreviousWordBoundary,
1488 cx: &mut ViewContext<Self>,
1489 ) {
1490 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1491 let mut selections = self.selections(cx).to_vec();
1492 {
1493 for selection in &mut selections {
1494 let head = selection.head().to_display_point(&display_map, Bias::Left);
1495 let new_head = movement::prev_word_boundary(&display_map, head).unwrap();
1496 let anchor = display_map.anchor_before(new_head, Bias::Left);
1497 selection.start = anchor.clone();
1498 selection.end = anchor;
1499 selection.reversed = false;
1500 selection.goal = SelectionGoal::None;
1501 }
1502 }
1503 self.update_selections(selections, true, cx);
1504 }
1505
1506 pub fn select_to_previous_word_boundary(
1507 &mut self,
1508 _: &SelectToPreviousWordBoundary,
1509 cx: &mut ViewContext<Self>,
1510 ) {
1511 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1512 let mut selections = self.selections(cx).to_vec();
1513 {
1514 let buffer = self.buffer.read(cx);
1515 for selection in &mut selections {
1516 let head = selection.head().to_display_point(&display_map, Bias::Left);
1517 let new_head = movement::prev_word_boundary(&display_map, head).unwrap();
1518 let anchor = display_map.anchor_before(new_head, Bias::Left);
1519 selection.set_head(buffer, anchor);
1520 selection.goal = SelectionGoal::None;
1521 }
1522 }
1523 self.update_selections(selections, true, cx);
1524 }
1525
1526 pub fn delete_to_previous_word_boundary(
1527 &mut self,
1528 _: &DeleteToPreviousWordBoundary,
1529 cx: &mut ViewContext<Self>,
1530 ) {
1531 self.start_transaction(cx);
1532 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1533 let mut selections = self.selections(cx).to_vec();
1534 {
1535 let buffer = self.buffer.read(cx);
1536 for selection in &mut selections {
1537 let range = selection.point_range(buffer);
1538 if range.start == range.end {
1539 let head = selection.head().to_display_point(&display_map, Bias::Left);
1540 let cursor = display_map.anchor_before(
1541 movement::prev_word_boundary(&display_map, head).unwrap(),
1542 Bias::Right,
1543 );
1544 selection.set_head(&buffer, cursor);
1545 selection.goal = SelectionGoal::None;
1546 }
1547 }
1548 }
1549
1550 self.update_selections(selections, true, cx);
1551 self.insert(&Insert(String::new()), cx);
1552 self.end_transaction(cx);
1553 }
1554
1555 pub fn move_to_next_word_boundary(
1556 &mut self,
1557 _: &MoveToNextWordBoundary,
1558 cx: &mut ViewContext<Self>,
1559 ) {
1560 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1561 let mut selections = self.selections(cx).to_vec();
1562 {
1563 for selection in &mut selections {
1564 let head = selection.head().to_display_point(&display_map, Bias::Left);
1565 let new_head = movement::next_word_boundary(&display_map, head).unwrap();
1566 let anchor = display_map.anchor_before(new_head, Bias::Left);
1567 selection.start = anchor.clone();
1568 selection.end = anchor;
1569 selection.reversed = false;
1570 selection.goal = SelectionGoal::None;
1571 }
1572 }
1573 self.update_selections(selections, true, cx);
1574 }
1575
1576 pub fn select_to_next_word_boundary(
1577 &mut self,
1578 _: &SelectToNextWordBoundary,
1579 cx: &mut ViewContext<Self>,
1580 ) {
1581 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1582 let mut selections = self.selections(cx).to_vec();
1583 {
1584 let buffer = self.buffer.read(cx);
1585 for selection in &mut selections {
1586 let head = selection.head().to_display_point(&display_map, Bias::Left);
1587 let new_head = movement::next_word_boundary(&display_map, head).unwrap();
1588 let anchor = display_map.anchor_before(new_head, Bias::Left);
1589 selection.set_head(buffer, anchor);
1590 selection.goal = SelectionGoal::None;
1591 }
1592 }
1593 self.update_selections(selections, true, cx);
1594 }
1595
1596 pub fn delete_to_next_word_boundary(
1597 &mut self,
1598 _: &DeleteToNextWordBoundary,
1599 cx: &mut ViewContext<Self>,
1600 ) {
1601 self.start_transaction(cx);
1602 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1603 let mut selections = self.selections(cx).to_vec();
1604 {
1605 let buffer = self.buffer.read(cx);
1606 for selection in &mut selections {
1607 let range = selection.point_range(buffer);
1608 if range.start == range.end {
1609 let head = selection.head().to_display_point(&display_map, Bias::Left);
1610 let cursor = display_map.anchor_before(
1611 movement::next_word_boundary(&display_map, head).unwrap(),
1612 Bias::Right,
1613 );
1614 selection.set_head(&buffer, cursor);
1615 selection.goal = SelectionGoal::None;
1616 }
1617 }
1618 }
1619
1620 self.update_selections(selections, true, cx);
1621 self.insert(&Insert(String::new()), cx);
1622 self.end_transaction(cx);
1623 }
1624
1625 pub fn move_to_beginning_of_line(
1626 &mut self,
1627 _: &MoveToBeginningOfLine,
1628 cx: &mut ViewContext<Self>,
1629 ) {
1630 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1631 let mut selections = self.selections(cx).to_vec();
1632 {
1633 for selection in &mut selections {
1634 let head = selection.head().to_display_point(&display_map, Bias::Left);
1635 let new_head = movement::line_beginning(&display_map, head, true).unwrap();
1636 let anchor = display_map.anchor_before(new_head, Bias::Left);
1637 selection.start = anchor.clone();
1638 selection.end = anchor;
1639 selection.reversed = false;
1640 selection.goal = SelectionGoal::None;
1641 }
1642 }
1643 self.update_selections(selections, true, cx);
1644 }
1645
1646 pub fn select_to_beginning_of_line(
1647 &mut self,
1648 SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
1649 cx: &mut ViewContext<Self>,
1650 ) {
1651 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1652 let mut selections = self.selections(cx).to_vec();
1653 {
1654 let buffer = self.buffer.read(cx);
1655 for selection in &mut selections {
1656 let head = selection.head().to_display_point(&display_map, Bias::Left);
1657 let new_head =
1658 movement::line_beginning(&display_map, head, *toggle_indent).unwrap();
1659 let anchor = display_map.anchor_before(new_head, Bias::Left);
1660 selection.set_head(buffer, anchor);
1661 selection.goal = SelectionGoal::None;
1662 }
1663 }
1664 self.update_selections(selections, true, cx);
1665 }
1666
1667 pub fn delete_to_beginning_of_line(
1668 &mut self,
1669 _: &DeleteToBeginningOfLine,
1670 cx: &mut ViewContext<Self>,
1671 ) {
1672 self.start_transaction(cx);
1673 self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
1674 self.backspace(&Backspace, cx);
1675 self.end_transaction(cx);
1676 }
1677
1678 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
1679 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1680 let mut selections = self.selections(cx).to_vec();
1681 {
1682 for selection in &mut selections {
1683 let head = selection.head().to_display_point(&display_map, Bias::Left);
1684 let new_head = movement::line_end(&display_map, head).unwrap();
1685 let anchor = display_map.anchor_before(new_head, Bias::Left);
1686 selection.start = anchor.clone();
1687 selection.end = anchor;
1688 selection.reversed = false;
1689 selection.goal = SelectionGoal::None;
1690 }
1691 }
1692 self.update_selections(selections, true, cx);
1693 }
1694
1695 pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
1696 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1697 let mut selections = self.selections(cx).to_vec();
1698 {
1699 let buffer = self.buffer.read(cx);
1700 for selection in &mut selections {
1701 let head = selection.head().to_display_point(&display_map, Bias::Left);
1702 let new_head = movement::line_end(&display_map, head).unwrap();
1703 let anchor = display_map.anchor_before(new_head, Bias::Left);
1704 selection.set_head(buffer, anchor);
1705 selection.goal = SelectionGoal::None;
1706 }
1707 }
1708 self.update_selections(selections, true, cx);
1709 }
1710
1711 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
1712 self.start_transaction(cx);
1713 self.select_to_end_of_line(&SelectToEndOfLine, cx);
1714 self.delete(&Delete, cx);
1715 self.end_transaction(cx);
1716 }
1717
1718 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
1719 self.start_transaction(cx);
1720 self.select_to_end_of_line(&SelectToEndOfLine, cx);
1721 self.cut(&Cut, cx);
1722 self.end_transaction(cx);
1723 }
1724
1725 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
1726 let buffer = self.buffer.read(cx);
1727 let cursor = buffer.anchor_before(Point::new(0, 0));
1728 let selection = Selection {
1729 id: post_inc(&mut self.next_selection_id),
1730 start: cursor.clone(),
1731 end: cursor,
1732 reversed: false,
1733 goal: SelectionGoal::None,
1734 };
1735 self.update_selections(vec![selection], true, cx);
1736 }
1737
1738 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
1739 let mut selection = self.selections(cx).last().unwrap().clone();
1740 selection.set_head(self.buffer.read(cx), Anchor::min());
1741 self.update_selections(vec![selection], true, cx);
1742 }
1743
1744 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
1745 let buffer = self.buffer.read(cx);
1746 let cursor = buffer.anchor_before(buffer.max_point());
1747 let selection = Selection {
1748 id: post_inc(&mut self.next_selection_id),
1749 start: cursor.clone(),
1750 end: cursor,
1751 reversed: false,
1752 goal: SelectionGoal::None,
1753 };
1754 self.update_selections(vec![selection], true, cx);
1755 }
1756
1757 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
1758 let mut selection = self.selections(cx).last().unwrap().clone();
1759 selection.set_head(self.buffer.read(cx), Anchor::max());
1760 self.update_selections(vec![selection], true, cx);
1761 }
1762
1763 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
1764 let selection = Selection {
1765 id: post_inc(&mut self.next_selection_id),
1766 start: Anchor::min(),
1767 end: Anchor::max(),
1768 reversed: false,
1769 goal: SelectionGoal::None,
1770 };
1771 self.update_selections(vec![selection], false, cx);
1772 }
1773
1774 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
1775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1776 let mut selections = self.selections(cx).to_vec();
1777 let buffer = self.buffer.read(cx);
1778 let max_point = buffer.max_point();
1779 for selection in &mut selections {
1780 let rows = selection.spanned_rows(true, &display_map).buffer_rows;
1781 selection.start = buffer.anchor_before(Point::new(rows.start, 0));
1782 selection.end = buffer.anchor_before(cmp::min(max_point, Point::new(rows.end, 0)));
1783 selection.reversed = false;
1784 }
1785 self.update_selections(selections, true, cx);
1786 }
1787
1788 pub fn split_selection_into_lines(
1789 &mut self,
1790 _: &SplitSelectionIntoLines,
1791 cx: &mut ViewContext<Self>,
1792 ) {
1793 let selections = self.selections(cx);
1794 let buffer = self.buffer.read(cx);
1795
1796 let mut to_unfold = Vec::new();
1797 let mut new_selections = Vec::new();
1798 for selection in selections.iter() {
1799 let range = selection.point_range(buffer).sorted();
1800 if range.start.row != range.end.row {
1801 new_selections.push(Selection {
1802 id: post_inc(&mut self.next_selection_id),
1803 start: selection.start.clone(),
1804 end: selection.start.clone(),
1805 reversed: false,
1806 goal: SelectionGoal::None,
1807 });
1808 }
1809 for row in range.start.row + 1..range.end.row {
1810 let cursor = buffer.anchor_before(Point::new(row, buffer.line_len(row)));
1811 new_selections.push(Selection {
1812 id: post_inc(&mut self.next_selection_id),
1813 start: cursor.clone(),
1814 end: cursor,
1815 reversed: false,
1816 goal: SelectionGoal::None,
1817 });
1818 }
1819 new_selections.push(Selection {
1820 id: selection.id,
1821 start: selection.end.clone(),
1822 end: selection.end.clone(),
1823 reversed: false,
1824 goal: SelectionGoal::None,
1825 });
1826 to_unfold.push(range);
1827 }
1828 self.unfold_ranges(to_unfold, cx);
1829 self.update_selections(new_selections, true, cx);
1830 }
1831
1832 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
1833 self.add_selection(true, cx);
1834 }
1835
1836 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
1837 self.add_selection(false, cx);
1838 }
1839
1840 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
1841 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1842 let mut selections = self.selections(cx).to_vec();
1843 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
1844 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
1845 let range = oldest_selection.display_range(&display_map).sorted();
1846 let columns = cmp::min(range.start.column(), range.end.column())
1847 ..cmp::max(range.start.column(), range.end.column());
1848
1849 selections.clear();
1850 let mut stack = Vec::new();
1851 for row in range.start.row()..=range.end.row() {
1852 if let Some(selection) = self.build_columnar_selection(
1853 &display_map,
1854 row,
1855 &columns,
1856 oldest_selection.reversed,
1857 ) {
1858 stack.push(selection.id);
1859 selections.push(selection);
1860 }
1861 }
1862
1863 if above {
1864 stack.reverse();
1865 }
1866
1867 AddSelectionsState { above, stack }
1868 });
1869
1870 let last_added_selection = *state.stack.last().unwrap();
1871 let mut new_selections = Vec::new();
1872 if above == state.above {
1873 let end_row = if above {
1874 0
1875 } else {
1876 display_map.max_point().row()
1877 };
1878
1879 'outer: for selection in selections {
1880 if selection.id == last_added_selection {
1881 let range = selection.display_range(&display_map).sorted();
1882 debug_assert_eq!(range.start.row(), range.end.row());
1883 let mut row = range.start.row();
1884 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
1885 {
1886 start..end
1887 } else {
1888 cmp::min(range.start.column(), range.end.column())
1889 ..cmp::max(range.start.column(), range.end.column())
1890 };
1891
1892 while row != end_row {
1893 if above {
1894 row -= 1;
1895 } else {
1896 row += 1;
1897 }
1898
1899 if let Some(new_selection) = self.build_columnar_selection(
1900 &display_map,
1901 row,
1902 &columns,
1903 selection.reversed,
1904 ) {
1905 state.stack.push(new_selection.id);
1906 if above {
1907 new_selections.push(new_selection);
1908 new_selections.push(selection);
1909 } else {
1910 new_selections.push(selection);
1911 new_selections.push(new_selection);
1912 }
1913
1914 continue 'outer;
1915 }
1916 }
1917 }
1918
1919 new_selections.push(selection);
1920 }
1921 } else {
1922 new_selections = selections;
1923 new_selections.retain(|s| s.id != last_added_selection);
1924 state.stack.pop();
1925 }
1926
1927 self.update_selections(new_selections, true, cx);
1928 if state.stack.len() > 1 {
1929 self.add_selections_state = Some(state);
1930 }
1931 }
1932
1933 pub fn select_larger_syntax_node(
1934 &mut self,
1935 _: &SelectLargerSyntaxNode,
1936 cx: &mut ViewContext<Self>,
1937 ) {
1938 let old_selections = self.selections(cx);
1939 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1940 let buffer = self.buffer.read(cx);
1941
1942 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
1943 let mut selected_larger_node = false;
1944 let mut new_selection_ranges = Vec::new();
1945 for selection in old_selections.iter() {
1946 let old_range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
1947 let mut new_range = old_range.clone();
1948 while let Some(containing_range) = buffer.range_for_syntax_ancestor(new_range.clone()) {
1949 new_range = containing_range;
1950 if !display_map.intersects_fold(new_range.start)
1951 && !display_map.intersects_fold(new_range.end)
1952 {
1953 break;
1954 }
1955 }
1956
1957 selected_larger_node |= new_range != old_range;
1958 new_selection_ranges.push((selection.id, new_range, selection.reversed));
1959 }
1960
1961 if selected_larger_node {
1962 stack.push(old_selections);
1963 new_selection_ranges.sort_unstable_by_key(|(_, range, _)| range.start.clone());
1964 let new_selections = new_selection_ranges
1965 .into_iter()
1966 .map(|(id, range, reversed)| Selection {
1967 id,
1968 start: buffer.anchor_before(range.start),
1969 end: buffer.anchor_before(range.end),
1970 reversed,
1971 goal: SelectionGoal::None,
1972 })
1973 .collect();
1974 self.update_selections(new_selections, true, cx);
1975 }
1976 self.select_larger_syntax_node_stack = stack;
1977 }
1978
1979 pub fn select_smaller_syntax_node(
1980 &mut self,
1981 _: &SelectSmallerSyntaxNode,
1982 cx: &mut ViewContext<Self>,
1983 ) {
1984 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
1985 if let Some(selections) = stack.pop() {
1986 self.update_selections(selections.to_vec(), true, cx);
1987 }
1988 self.select_larger_syntax_node_stack = stack;
1989 }
1990
1991 pub fn move_to_enclosing_bracket(
1992 &mut self,
1993 _: &MoveToEnclosingBracket,
1994 cx: &mut ViewContext<Self>,
1995 ) {
1996 let mut selections = self.selections(cx).to_vec();
1997 let buffer = self.buffer.read(cx.as_ref());
1998 for selection in &mut selections {
1999 let selection_range = selection.offset_range(buffer);
2000 if let Some((open_range, close_range)) =
2001 buffer.enclosing_bracket_ranges(selection_range.clone())
2002 {
2003 let close_range = close_range.to_inclusive();
2004 let destination = if close_range.contains(&selection_range.start)
2005 && close_range.contains(&selection_range.end)
2006 {
2007 open_range.end
2008 } else {
2009 *close_range.start()
2010 };
2011 selection.start = buffer.anchor_before(destination);
2012 selection.end = selection.start.clone();
2013 }
2014 }
2015
2016 self.update_selections(selections, true, cx);
2017 }
2018
2019 fn build_columnar_selection(
2020 &mut self,
2021 display_map: &DisplayMapSnapshot,
2022 row: u32,
2023 columns: &Range<u32>,
2024 reversed: bool,
2025 ) -> Option<Selection> {
2026 let is_empty = columns.start == columns.end;
2027 let line_len = display_map.line_len(row);
2028 if columns.start < line_len || (is_empty && columns.start == line_len) {
2029 let start = DisplayPoint::new(row, columns.start);
2030 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
2031 Some(Selection {
2032 id: post_inc(&mut self.next_selection_id),
2033 start: display_map.anchor_before(start, Bias::Left),
2034 end: display_map.anchor_before(end, Bias::Left),
2035 reversed,
2036 goal: SelectionGoal::ColumnRange {
2037 start: columns.start,
2038 end: columns.end,
2039 },
2040 })
2041 } else {
2042 None
2043 }
2044 }
2045
2046 pub fn active_selection_sets<'a>(
2047 &'a self,
2048 cx: &'a AppContext,
2049 ) -> impl 'a + Iterator<Item = SelectionSetId> {
2050 let buffer = self.buffer.read(cx);
2051 let replica_id = buffer.replica_id();
2052 buffer
2053 .selection_sets()
2054 .filter(move |(set_id, set)| {
2055 set.active && (set_id.replica_id != replica_id || **set_id == self.selection_set_id)
2056 })
2057 .map(|(set_id, _)| *set_id)
2058 }
2059
2060 pub fn selections_in_range<'a>(
2061 &'a self,
2062 set_id: SelectionSetId,
2063 range: Range<DisplayPoint>,
2064 cx: &'a mut MutableAppContext,
2065 ) -> impl 'a + Iterator<Item = Range<DisplayPoint>> {
2066 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2067 let buffer = self.buffer.read(cx);
2068 let selections = &buffer.selection_set(set_id).unwrap().selections;
2069 let start = display_map.anchor_before(range.start, Bias::Left);
2070 let start_index = self.selection_insertion_index(selections, &start, cx);
2071 let pending_selection = if set_id.replica_id == self.buffer.read(cx).replica_id() {
2072 self.pending_selection.as_ref().and_then(|s| {
2073 let selection_range = s.display_range(&display_map);
2074 if selection_range.start <= range.end || selection_range.end <= range.end {
2075 Some(selection_range)
2076 } else {
2077 None
2078 }
2079 })
2080 } else {
2081 None
2082 };
2083 selections[start_index..]
2084 .iter()
2085 .map(move |s| s.display_range(&display_map))
2086 .take_while(move |r| r.start <= range.end || r.end <= range.end)
2087 .chain(pending_selection)
2088 }
2089
2090 fn selection_insertion_index(
2091 &self,
2092 selections: &[Selection],
2093 start: &Anchor,
2094 cx: &AppContext,
2095 ) -> usize {
2096 let buffer = self.buffer.read(cx);
2097 match selections.binary_search_by(|probe| probe.start.cmp(&start, buffer).unwrap()) {
2098 Ok(index) => index,
2099 Err(index) => {
2100 if index > 0
2101 && selections[index - 1].end.cmp(&start, buffer).unwrap() == Ordering::Greater
2102 {
2103 index - 1
2104 } else {
2105 index
2106 }
2107 }
2108 }
2109 }
2110
2111 fn selections(&mut self, cx: &mut ViewContext<Self>) -> Arc<[Selection]> {
2112 self.end_selection(cx);
2113 let buffer = self.buffer.read(cx);
2114 buffer
2115 .selection_set(self.selection_set_id)
2116 .unwrap()
2117 .selections
2118 .clone()
2119 }
2120
2121 fn update_selections(
2122 &mut self,
2123 mut selections: Vec<Selection>,
2124 autoscroll: bool,
2125 cx: &mut ViewContext<Self>,
2126 ) {
2127 // Merge overlapping selections.
2128 let buffer = self.buffer.read(cx);
2129 let mut i = 1;
2130 while i < selections.len() {
2131 if selections[i - 1]
2132 .end
2133 .cmp(&selections[i].start, buffer)
2134 .unwrap()
2135 >= Ordering::Equal
2136 {
2137 let removed = selections.remove(i);
2138 if removed.start.cmp(&selections[i - 1].start, buffer).unwrap() < Ordering::Equal {
2139 selections[i - 1].start = removed.start;
2140 }
2141 if removed.end.cmp(&selections[i - 1].end, buffer).unwrap() > Ordering::Equal {
2142 selections[i - 1].end = removed.end;
2143 }
2144 } else {
2145 i += 1;
2146 }
2147 }
2148
2149 self.buffer.update(cx, |buffer, cx| {
2150 buffer
2151 .update_selection_set(self.selection_set_id, selections, cx)
2152 .unwrap();
2153 });
2154 self.pause_cursor_blinking(cx);
2155
2156 if autoscroll {
2157 self.autoscroll_requested = true;
2158 cx.notify();
2159 }
2160
2161 self.add_selections_state = None;
2162 self.select_larger_syntax_node_stack.clear();
2163 }
2164
2165 fn start_transaction(&self, cx: &mut ViewContext<Self>) {
2166 self.buffer.update(cx, |buffer, _| {
2167 buffer
2168 .start_transaction(Some(self.selection_set_id))
2169 .unwrap()
2170 });
2171 }
2172
2173 fn end_transaction(&self, cx: &mut ViewContext<Self>) {
2174 self.buffer.update(cx, |buffer, cx| {
2175 buffer
2176 .end_transaction(Some(self.selection_set_id), cx)
2177 .unwrap()
2178 });
2179 }
2180
2181 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
2182 log::info!("Editor::page_up");
2183 }
2184
2185 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
2186 log::info!("Editor::page_down");
2187 }
2188
2189 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
2190 let mut fold_ranges = Vec::new();
2191
2192 let selections = self.selections(cx);
2193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2194 for selection in selections.iter() {
2195 let range = selection.display_range(&display_map).sorted();
2196 let buffer_start_row = range.start.to_buffer_point(&display_map, Bias::Left).row;
2197
2198 for row in (0..=range.end.row()).rev() {
2199 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
2200 let fold_range = self.foldable_range_for_line(&display_map, row);
2201 if fold_range.end.row >= buffer_start_row {
2202 fold_ranges.push(fold_range);
2203 if row <= range.start.row() {
2204 break;
2205 }
2206 }
2207 }
2208 }
2209 }
2210
2211 self.fold_ranges(fold_ranges, cx);
2212 }
2213
2214 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
2215 let selections = self.selections(cx);
2216 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2217 let buffer = self.buffer.read(cx);
2218 let ranges = selections
2219 .iter()
2220 .map(|s| {
2221 let range = s.display_range(&display_map).sorted();
2222 let mut start = range.start.to_buffer_point(&display_map, Bias::Left);
2223 let mut end = range.end.to_buffer_point(&display_map, Bias::Left);
2224 start.column = 0;
2225 end.column = buffer.line_len(end.row);
2226 start..end
2227 })
2228 .collect::<Vec<_>>();
2229 self.unfold_ranges(ranges, cx);
2230 }
2231
2232 fn is_line_foldable(&self, display_map: &DisplayMapSnapshot, display_row: u32) -> bool {
2233 let max_point = display_map.max_point();
2234 if display_row >= max_point.row() {
2235 false
2236 } else {
2237 let (start_indent, is_blank) = display_map.line_indent(display_row);
2238 if is_blank {
2239 false
2240 } else {
2241 for display_row in display_row + 1..=max_point.row() {
2242 let (indent, is_blank) = display_map.line_indent(display_row);
2243 if !is_blank {
2244 return indent > start_indent;
2245 }
2246 }
2247 false
2248 }
2249 }
2250 }
2251
2252 fn foldable_range_for_line(
2253 &self,
2254 display_map: &DisplayMapSnapshot,
2255 start_row: u32,
2256 ) -> Range<Point> {
2257 let max_point = display_map.max_point();
2258
2259 let (start_indent, _) = display_map.line_indent(start_row);
2260 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
2261 let mut end = None;
2262 for row in start_row + 1..=max_point.row() {
2263 let (indent, is_blank) = display_map.line_indent(row);
2264 if !is_blank && indent <= start_indent {
2265 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
2266 break;
2267 }
2268 }
2269
2270 let end = end.unwrap_or(max_point);
2271 return start.to_buffer_point(display_map, Bias::Left)
2272 ..end.to_buffer_point(display_map, Bias::Left);
2273 }
2274
2275 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
2276 let selections = self.selections(cx);
2277 let buffer = self.buffer.read(cx);
2278 let ranges = selections
2279 .iter()
2280 .map(|s| s.point_range(buffer).sorted())
2281 .collect();
2282 self.fold_ranges(ranges, cx);
2283 }
2284
2285 fn fold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2286 if !ranges.is_empty() {
2287 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
2288 self.autoscroll_requested = true;
2289 cx.notify();
2290 }
2291 }
2292
2293 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2294 if !ranges.is_empty() {
2295 self.display_map
2296 .update(cx, |map, cx| map.unfold(ranges, cx));
2297 self.autoscroll_requested = true;
2298 cx.notify();
2299 }
2300 }
2301
2302 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
2303 self.display_map
2304 .update(cx, |map, cx| map.snapshot(cx))
2305 .longest_row()
2306 }
2307
2308 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
2309 self.display_map
2310 .update(cx, |map, cx| map.snapshot(cx))
2311 .max_point()
2312 }
2313
2314 pub fn text(&self, cx: &AppContext) -> String {
2315 self.buffer.read(cx).text()
2316 }
2317
2318 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
2319 self.display_map
2320 .update(cx, |map, cx| map.snapshot(cx))
2321 .text()
2322 }
2323
2324 // pub fn font_size(&self) -> f32 {
2325 // self.settings.font_size
2326 // }
2327
2328 pub fn set_wrap_width(&self, width: f32, cx: &mut MutableAppContext) -> bool {
2329 self.display_map
2330 .update(cx, |map, cx| map.set_wrap_width(Some(width), cx))
2331 }
2332
2333 fn next_blink_epoch(&mut self) -> usize {
2334 self.blink_epoch += 1;
2335 self.blink_epoch
2336 }
2337
2338 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
2339 self.show_local_cursors = true;
2340 cx.notify();
2341
2342 let epoch = self.next_blink_epoch();
2343 cx.spawn(|this, mut cx| {
2344 let this = this.downgrade();
2345 async move {
2346 Timer::after(CURSOR_BLINK_INTERVAL).await;
2347 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2348 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
2349 }
2350 }
2351 })
2352 .detach();
2353 }
2354
2355 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2356 if epoch == self.blink_epoch {
2357 self.blinking_paused = false;
2358 self.blink_cursors(epoch, cx);
2359 }
2360 }
2361
2362 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2363 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
2364 self.show_local_cursors = !self.show_local_cursors;
2365 cx.notify();
2366
2367 let epoch = self.next_blink_epoch();
2368 cx.spawn(|this, mut cx| {
2369 let this = this.downgrade();
2370 async move {
2371 Timer::after(CURSOR_BLINK_INTERVAL).await;
2372 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2373 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
2374 }
2375 }
2376 })
2377 .detach();
2378 }
2379 }
2380
2381 pub fn show_local_cursors(&self) -> bool {
2382 self.show_local_cursors
2383 }
2384
2385 fn on_buffer_changed(&mut self, _: ModelHandle<Buffer>, cx: &mut ViewContext<Self>) {
2386 cx.notify();
2387 }
2388
2389 fn on_buffer_event(
2390 &mut self,
2391 _: ModelHandle<Buffer>,
2392 event: &buffer::Event,
2393 cx: &mut ViewContext<Self>,
2394 ) {
2395 match event {
2396 buffer::Event::Edited => cx.emit(Event::Edited),
2397 buffer::Event::Dirtied => cx.emit(Event::Dirtied),
2398 buffer::Event::Saved => cx.emit(Event::Saved),
2399 buffer::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
2400 buffer::Event::Reloaded => cx.emit(Event::FileHandleChanged),
2401 buffer::Event::Closed => cx.emit(Event::Closed),
2402 buffer::Event::Reparsed => {}
2403 }
2404 }
2405
2406 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
2407 cx.notify();
2408 }
2409}
2410
2411impl Snapshot {
2412 pub fn is_empty(&self) -> bool {
2413 self.display_snapshot.is_empty()
2414 }
2415
2416 pub fn is_focused(&self) -> bool {
2417 self.is_focused
2418 }
2419
2420 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
2421 self.placeholder_text.as_ref()
2422 }
2423
2424 pub fn buffer_row_count(&self) -> u32 {
2425 self.display_snapshot.buffer_row_count()
2426 }
2427
2428 pub fn buffer_rows(&self, start_row: u32) -> BufferRows {
2429 self.display_snapshot.buffer_rows(start_row)
2430 }
2431
2432 pub fn highlighted_chunks_for_rows(
2433 &mut self,
2434 display_rows: Range<u32>,
2435 ) -> display_map::HighlightedChunks {
2436 self.display_snapshot
2437 .highlighted_chunks_for_rows(display_rows)
2438 }
2439
2440 pub fn scroll_position(&self) -> Vector2F {
2441 compute_scroll_position(
2442 &self.display_snapshot,
2443 self.scroll_position,
2444 &self.scroll_top_anchor,
2445 )
2446 }
2447
2448 pub fn max_point(&self) -> DisplayPoint {
2449 self.display_snapshot.max_point()
2450 }
2451
2452 pub fn longest_row(&self) -> u32 {
2453 self.display_snapshot.longest_row()
2454 }
2455
2456 pub fn line_len(&self, display_row: u32) -> u32 {
2457 self.display_snapshot.line_len(display_row)
2458 }
2459
2460 pub fn line(&self, display_row: u32) -> String {
2461 self.display_snapshot.line(display_row)
2462 }
2463
2464 pub fn prev_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2465 self.display_snapshot.prev_row_boundary(point)
2466 }
2467
2468 pub fn next_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2469 self.display_snapshot.next_row_boundary(point)
2470 }
2471}
2472
2473impl EditorSettings {
2474 #[cfg(any(test, feature = "test-support"))]
2475 pub fn test(cx: &AppContext) -> Self {
2476 Self {
2477 tab_size: 4,
2478 style: {
2479 let font_cache: &gpui::FontCache = cx.font_cache();
2480 let font_family_name = Arc::from("Monaco");
2481 let font_properties = Default::default();
2482 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
2483 let font_id = font_cache
2484 .select_font(font_family_id, &font_properties)
2485 .unwrap();
2486 EditorStyle {
2487 text: TextStyle {
2488 font_family_name,
2489 font_family_id,
2490 font_id,
2491 font_size: 14.,
2492 color: Color::from_u32(0xff0000ff),
2493 font_properties,
2494 underline: false,
2495 },
2496 placeholder_text: None,
2497 background: Default::default(),
2498 gutter_background: Default::default(),
2499 active_line_background: Default::default(),
2500 line_number: Default::default(),
2501 line_number_active: Default::default(),
2502 selection: Default::default(),
2503 guest_selections: Default::default(),
2504 syntax: Default::default(),
2505 }
2506 },
2507 }
2508 }
2509}
2510
2511fn compute_scroll_position(
2512 snapshot: &DisplayMapSnapshot,
2513 mut scroll_position: Vector2F,
2514 scroll_top_anchor: &Anchor,
2515) -> Vector2F {
2516 let scroll_top = scroll_top_anchor
2517 .to_display_point(snapshot, Bias::Left)
2518 .row() as f32;
2519 scroll_position.set_y(scroll_top + scroll_position.y());
2520 scroll_position
2521}
2522
2523pub enum Event {
2524 Activate,
2525 Edited,
2526 Blurred,
2527 Dirtied,
2528 Saved,
2529 FileHandleChanged,
2530 Closed,
2531}
2532
2533impl Entity for Editor {
2534 type Event = Event;
2535
2536 fn release(&mut self, cx: &mut MutableAppContext) {
2537 self.buffer.update(cx, |buffer, cx| {
2538 buffer
2539 .remove_selection_set(self.selection_set_id, cx)
2540 .unwrap();
2541 });
2542 }
2543}
2544
2545impl View for Editor {
2546 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2547 let settings = self.build_settings.borrow_mut()(cx);
2548 self.display_map.update(cx, |map, cx| {
2549 map.set_font(
2550 settings.style.text.font_id,
2551 settings.style.text.font_size,
2552 cx,
2553 )
2554 });
2555 EditorElement::new(self.handle.clone(), settings).boxed()
2556 }
2557
2558 fn ui_name() -> &'static str {
2559 "Editor"
2560 }
2561
2562 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2563 self.focused = true;
2564 self.blink_cursors(self.blink_epoch, cx);
2565 self.buffer.update(cx, |buffer, cx| {
2566 buffer
2567 .set_active_selection_set(Some(self.selection_set_id), cx)
2568 .unwrap();
2569 });
2570 }
2571
2572 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
2573 self.focused = false;
2574 self.show_local_cursors = false;
2575 self.buffer.update(cx, |buffer, cx| {
2576 buffer.set_active_selection_set(None, cx).unwrap();
2577 });
2578 cx.emit(Event::Blurred);
2579 cx.notify();
2580 }
2581
2582 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
2583 let mut cx = Self::default_keymap_context();
2584 let mode = match self.mode {
2585 EditorMode::SingleLine => "single_line",
2586 EditorMode::AutoHeight { .. } => "auto_height",
2587 EditorMode::Full => "full",
2588 };
2589 cx.map.insert("mode".into(), mode.into());
2590 cx
2591 }
2592}
2593
2594impl SelectionExt for Selection {
2595 fn display_range(&self, map: &DisplayMapSnapshot) -> Range<DisplayPoint> {
2596 let start = self.start.to_display_point(map, Bias::Left);
2597 let end = self.end.to_display_point(map, Bias::Left);
2598 if self.reversed {
2599 end..start
2600 } else {
2601 start..end
2602 }
2603 }
2604
2605 fn spanned_rows(
2606 &self,
2607 include_end_if_at_line_start: bool,
2608 map: &DisplayMapSnapshot,
2609 ) -> SpannedRows {
2610 let display_start = self.start.to_display_point(map, Bias::Left);
2611 let mut display_end = self.end.to_display_point(map, Bias::Right);
2612 if !include_end_if_at_line_start
2613 && display_end.row() != map.max_point().row()
2614 && display_start.row() != display_end.row()
2615 && display_end.column() == 0
2616 {
2617 *display_end.row_mut() -= 1;
2618 }
2619
2620 let (display_start, buffer_start) = map.prev_row_boundary(display_start);
2621 let (display_end, buffer_end) = map.next_row_boundary(display_end);
2622
2623 SpannedRows {
2624 buffer_rows: buffer_start.row..buffer_end.row + 1,
2625 display_rows: display_start.row()..display_end.row() + 1,
2626 }
2627 }
2628}
2629
2630#[cfg(test)]
2631mod tests {
2632 use super::*;
2633 use crate::test::sample_text;
2634 use buffer::{History, Point};
2635 use unindent::Unindent;
2636
2637 #[gpui::test]
2638 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
2639 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2640 let settings = EditorSettings::test(cx);
2641 let (_, editor) =
2642 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
2643
2644 editor.update(cx, |view, cx| {
2645 view.begin_selection(DisplayPoint::new(2, 2), false, cx);
2646 });
2647
2648 assert_eq!(
2649 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2650 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
2651 );
2652
2653 editor.update(cx, |view, cx| {
2654 view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2655 });
2656
2657 assert_eq!(
2658 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2659 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2660 );
2661
2662 editor.update(cx, |view, cx| {
2663 view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2664 });
2665
2666 assert_eq!(
2667 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2668 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
2669 );
2670
2671 editor.update(cx, |view, cx| {
2672 view.end_selection(cx);
2673 view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2674 });
2675
2676 assert_eq!(
2677 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2678 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
2679 );
2680
2681 editor.update(cx, |view, cx| {
2682 view.begin_selection(DisplayPoint::new(3, 3), true, cx);
2683 view.update_selection(DisplayPoint::new(0, 0), Vector2F::zero(), cx);
2684 });
2685
2686 assert_eq!(
2687 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2688 [
2689 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
2690 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
2691 ]
2692 );
2693
2694 editor.update(cx, |view, cx| {
2695 view.end_selection(cx);
2696 });
2697
2698 assert_eq!(
2699 editor.update(cx, |view, cx| view.selection_ranges(cx)),
2700 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
2701 );
2702 }
2703
2704 #[gpui::test]
2705 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
2706 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2707 let settings = EditorSettings::test(cx);
2708 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
2709
2710 view.update(cx, |view, cx| {
2711 view.begin_selection(DisplayPoint::new(2, 2), false, cx);
2712 assert_eq!(
2713 view.selection_ranges(cx),
2714 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
2715 );
2716 });
2717
2718 view.update(cx, |view, cx| {
2719 view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
2720 assert_eq!(
2721 view.selection_ranges(cx),
2722 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2723 );
2724 });
2725
2726 view.update(cx, |view, cx| {
2727 view.cancel(&Cancel, cx);
2728 view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2729 assert_eq!(
2730 view.selection_ranges(cx),
2731 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
2732 );
2733 });
2734 }
2735
2736 #[gpui::test]
2737 fn test_cancel(cx: &mut gpui::MutableAppContext) {
2738 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
2739 let settings = EditorSettings::test(cx);
2740 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
2741
2742 view.update(cx, |view, cx| {
2743 view.begin_selection(DisplayPoint::new(3, 4), false, cx);
2744 view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
2745 view.end_selection(cx);
2746
2747 view.begin_selection(DisplayPoint::new(0, 1), true, cx);
2748 view.update_selection(DisplayPoint::new(0, 3), Vector2F::zero(), cx);
2749 view.end_selection(cx);
2750 assert_eq!(
2751 view.selection_ranges(cx),
2752 [
2753 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
2754 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
2755 ]
2756 );
2757 });
2758
2759 view.update(cx, |view, cx| {
2760 view.cancel(&Cancel, cx);
2761 assert_eq!(
2762 view.selection_ranges(cx),
2763 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
2764 );
2765 });
2766
2767 view.update(cx, |view, cx| {
2768 view.cancel(&Cancel, cx);
2769 assert_eq!(
2770 view.selection_ranges(cx),
2771 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
2772 );
2773 });
2774 }
2775
2776 #[gpui::test]
2777 fn test_fold(cx: &mut gpui::MutableAppContext) {
2778 let buffer = cx.add_model(|cx| {
2779 Buffer::new(
2780 0,
2781 "
2782 impl Foo {
2783 // Hello!
2784
2785 fn a() {
2786 1
2787 }
2788
2789 fn b() {
2790 2
2791 }
2792
2793 fn c() {
2794 3
2795 }
2796 }
2797 "
2798 .unindent(),
2799 cx,
2800 )
2801 });
2802 let settings = EditorSettings::test(&cx);
2803 let (_, view) = cx.add_window(Default::default(), |cx| {
2804 build_editor(buffer.clone(), settings, cx)
2805 });
2806
2807 view.update(cx, |view, cx| {
2808 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
2809 .unwrap();
2810 view.fold(&Fold, cx);
2811 assert_eq!(
2812 view.display_text(cx),
2813 "
2814 impl Foo {
2815 // Hello!
2816
2817 fn a() {
2818 1
2819 }
2820
2821 fn b() {…
2822 }
2823
2824 fn c() {…
2825 }
2826 }
2827 "
2828 .unindent(),
2829 );
2830
2831 view.fold(&Fold, cx);
2832 assert_eq!(
2833 view.display_text(cx),
2834 "
2835 impl Foo {…
2836 }
2837 "
2838 .unindent(),
2839 );
2840
2841 view.unfold(&Unfold, cx);
2842 assert_eq!(
2843 view.display_text(cx),
2844 "
2845 impl Foo {
2846 // Hello!
2847
2848 fn a() {
2849 1
2850 }
2851
2852 fn b() {…
2853 }
2854
2855 fn c() {…
2856 }
2857 }
2858 "
2859 .unindent(),
2860 );
2861
2862 view.unfold(&Unfold, cx);
2863 assert_eq!(view.display_text(cx), buffer.read(cx).text());
2864 });
2865 }
2866
2867 #[gpui::test]
2868 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
2869 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
2870 let settings = EditorSettings::test(&cx);
2871 let (_, view) = cx.add_window(Default::default(), |cx| {
2872 build_editor(buffer.clone(), settings, cx)
2873 });
2874
2875 buffer.update(cx, |buffer, cx| {
2876 buffer.edit(
2877 vec![
2878 Point::new(1, 0)..Point::new(1, 0),
2879 Point::new(1, 1)..Point::new(1, 1),
2880 ],
2881 "\t",
2882 cx,
2883 );
2884 });
2885
2886 view.update(cx, |view, cx| {
2887 assert_eq!(
2888 view.selection_ranges(cx),
2889 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
2890 );
2891
2892 view.move_down(&MoveDown, cx);
2893 assert_eq!(
2894 view.selection_ranges(cx),
2895 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
2896 );
2897
2898 view.move_right(&MoveRight, cx);
2899 assert_eq!(
2900 view.selection_ranges(cx),
2901 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
2902 );
2903
2904 view.move_left(&MoveLeft, cx);
2905 assert_eq!(
2906 view.selection_ranges(cx),
2907 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
2908 );
2909
2910 view.move_up(&MoveUp, cx);
2911 assert_eq!(
2912 view.selection_ranges(cx),
2913 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
2914 );
2915
2916 view.move_to_end(&MoveToEnd, cx);
2917 assert_eq!(
2918 view.selection_ranges(cx),
2919 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
2920 );
2921
2922 view.move_to_beginning(&MoveToBeginning, cx);
2923 assert_eq!(
2924 view.selection_ranges(cx),
2925 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
2926 );
2927
2928 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
2929 .unwrap();
2930 view.select_to_beginning(&SelectToBeginning, cx);
2931 assert_eq!(
2932 view.selection_ranges(cx),
2933 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
2934 );
2935
2936 view.select_to_end(&SelectToEnd, cx);
2937 assert_eq!(
2938 view.selection_ranges(cx),
2939 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
2940 );
2941 });
2942 }
2943
2944 #[gpui::test]
2945 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
2946 let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx));
2947 let settings = EditorSettings::test(&cx);
2948 let (_, view) = cx.add_window(Default::default(), |cx| {
2949 build_editor(buffer.clone(), settings, cx)
2950 });
2951
2952 assert_eq!('ⓐ'.len_utf8(), 3);
2953 assert_eq!('α'.len_utf8(), 2);
2954
2955 view.update(cx, |view, cx| {
2956 view.fold_ranges(
2957 vec![
2958 Point::new(0, 6)..Point::new(0, 12),
2959 Point::new(1, 2)..Point::new(1, 4),
2960 Point::new(2, 4)..Point::new(2, 8),
2961 ],
2962 cx,
2963 );
2964 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
2965
2966 view.move_right(&MoveRight, cx);
2967 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
2968 view.move_right(&MoveRight, cx);
2969 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
2970 view.move_right(&MoveRight, cx);
2971 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
2972
2973 view.move_down(&MoveDown, cx);
2974 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
2975 view.move_left(&MoveLeft, cx);
2976 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
2977 view.move_left(&MoveLeft, cx);
2978 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
2979
2980 view.move_down(&MoveDown, cx);
2981 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
2982 view.move_right(&MoveRight, cx);
2983 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
2984 view.move_right(&MoveRight, cx);
2985 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
2986 view.move_right(&MoveRight, cx);
2987 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
2988
2989 view.move_up(&MoveUp, cx);
2990 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
2991 view.move_up(&MoveUp, cx);
2992 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
2993 view.move_left(&MoveLeft, cx);
2994 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
2995 view.move_left(&MoveLeft, cx);
2996 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
2997 view.move_left(&MoveLeft, cx);
2998 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
2999 });
3000 }
3001
3002 #[gpui::test]
3003 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
3004 let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx));
3005 let settings = EditorSettings::test(&cx);
3006 let (_, view) = cx.add_window(Default::default(), |cx| {
3007 build_editor(buffer.clone(), settings, cx)
3008 });
3009 view.update(cx, |view, cx| {
3010 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
3011 .unwrap();
3012
3013 view.move_down(&MoveDown, cx);
3014 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
3015
3016 view.move_down(&MoveDown, cx);
3017 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3018
3019 view.move_down(&MoveDown, cx);
3020 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3021
3022 view.move_down(&MoveDown, cx);
3023 assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
3024
3025 view.move_up(&MoveUp, cx);
3026 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3027
3028 view.move_up(&MoveUp, cx);
3029 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3030 });
3031 }
3032
3033 #[gpui::test]
3034 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
3035 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\n def", cx));
3036 let settings = EditorSettings::test(&cx);
3037 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3038 view.update(cx, |view, cx| {
3039 view.select_display_ranges(
3040 &[
3041 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3042 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3043 ],
3044 cx,
3045 )
3046 .unwrap();
3047 });
3048
3049 view.update(cx, |view, cx| {
3050 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3051 assert_eq!(
3052 view.selection_ranges(cx),
3053 &[
3054 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3055 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3056 ]
3057 );
3058 });
3059
3060 view.update(cx, |view, cx| {
3061 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3062 assert_eq!(
3063 view.selection_ranges(cx),
3064 &[
3065 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3066 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3067 ]
3068 );
3069 });
3070
3071 view.update(cx, |view, cx| {
3072 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3073 assert_eq!(
3074 view.selection_ranges(cx),
3075 &[
3076 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3077 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3078 ]
3079 );
3080 });
3081
3082 view.update(cx, |view, cx| {
3083 view.move_to_end_of_line(&MoveToEndOfLine, cx);
3084 assert_eq!(
3085 view.selection_ranges(cx),
3086 &[
3087 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3088 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3089 ]
3090 );
3091 });
3092
3093 // Moving to the end of line again is a no-op.
3094 view.update(cx, |view, cx| {
3095 view.move_to_end_of_line(&MoveToEndOfLine, cx);
3096 assert_eq!(
3097 view.selection_ranges(cx),
3098 &[
3099 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3100 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3101 ]
3102 );
3103 });
3104
3105 view.update(cx, |view, cx| {
3106 view.move_left(&MoveLeft, cx);
3107 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3108 assert_eq!(
3109 view.selection_ranges(cx),
3110 &[
3111 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3112 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3113 ]
3114 );
3115 });
3116
3117 view.update(cx, |view, cx| {
3118 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3119 assert_eq!(
3120 view.selection_ranges(cx),
3121 &[
3122 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3123 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
3124 ]
3125 );
3126 });
3127
3128 view.update(cx, |view, cx| {
3129 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3130 assert_eq!(
3131 view.selection_ranges(cx),
3132 &[
3133 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3134 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3135 ]
3136 );
3137 });
3138
3139 view.update(cx, |view, cx| {
3140 view.select_to_end_of_line(&SelectToEndOfLine, cx);
3141 assert_eq!(
3142 view.selection_ranges(cx),
3143 &[
3144 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
3145 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
3146 ]
3147 );
3148 });
3149
3150 view.update(cx, |view, cx| {
3151 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
3152 assert_eq!(view.display_text(cx), "ab\n de");
3153 assert_eq!(
3154 view.selection_ranges(cx),
3155 &[
3156 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3157 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3158 ]
3159 );
3160 });
3161
3162 view.update(cx, |view, cx| {
3163 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
3164 assert_eq!(view.display_text(cx), "\n");
3165 assert_eq!(
3166 view.selection_ranges(cx),
3167 &[
3168 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3169 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3170 ]
3171 );
3172 });
3173 }
3174
3175 #[gpui::test]
3176 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
3177 let buffer =
3178 cx.add_model(|cx| Buffer::new(0, "use std::str::{foo, bar}\n\n {baz.qux()}", cx));
3179 let settings = EditorSettings::test(&cx);
3180 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3181 view.update(cx, |view, cx| {
3182 view.select_display_ranges(
3183 &[
3184 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
3185 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
3186 ],
3187 cx,
3188 )
3189 .unwrap();
3190 });
3191
3192 view.update(cx, |view, cx| {
3193 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3194 assert_eq!(
3195 view.selection_ranges(cx),
3196 &[
3197 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3198 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3199 ]
3200 );
3201 });
3202
3203 view.update(cx, |view, cx| {
3204 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3205 assert_eq!(
3206 view.selection_ranges(cx),
3207 &[
3208 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3209 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
3210 ]
3211 );
3212 });
3213
3214 view.update(cx, |view, cx| {
3215 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3216 assert_eq!(
3217 view.selection_ranges(cx),
3218 &[
3219 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
3220 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
3221 ]
3222 );
3223 });
3224
3225 view.update(cx, |view, cx| {
3226 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3227 assert_eq!(
3228 view.selection_ranges(cx),
3229 &[
3230 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3231 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3232 ]
3233 );
3234 });
3235
3236 view.update(cx, |view, cx| {
3237 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3238 assert_eq!(
3239 view.selection_ranges(cx),
3240 &[
3241 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3242 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
3243 ]
3244 );
3245 });
3246
3247 view.update(cx, |view, cx| {
3248 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3249 assert_eq!(
3250 view.selection_ranges(cx),
3251 &[
3252 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3253 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
3254 ]
3255 );
3256 });
3257
3258 view.update(cx, |view, cx| {
3259 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3260 assert_eq!(
3261 view.selection_ranges(cx),
3262 &[
3263 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3264 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3265 ]
3266 );
3267 });
3268
3269 view.update(cx, |view, cx| {
3270 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3271 assert_eq!(
3272 view.selection_ranges(cx),
3273 &[
3274 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3275 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3276 ]
3277 );
3278 });
3279
3280 view.update(cx, |view, cx| {
3281 view.move_right(&MoveRight, cx);
3282 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3283 assert_eq!(
3284 view.selection_ranges(cx),
3285 &[
3286 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3287 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3288 ]
3289 );
3290 });
3291
3292 view.update(cx, |view, cx| {
3293 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3294 assert_eq!(
3295 view.selection_ranges(cx),
3296 &[
3297 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
3298 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
3299 ]
3300 );
3301 });
3302
3303 view.update(cx, |view, cx| {
3304 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
3305 assert_eq!(
3306 view.selection_ranges(cx),
3307 &[
3308 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3309 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3310 ]
3311 );
3312 });
3313 }
3314
3315 #[gpui::test]
3316 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
3317 let buffer =
3318 cx.add_model(|cx| Buffer::new(0, "use one::{\n two::three::four::five\n};", cx));
3319 let settings = EditorSettings::test(&cx);
3320 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3321
3322 view.update(cx, |view, cx| {
3323 view.set_wrap_width(140., cx);
3324 assert_eq!(
3325 view.display_text(cx),
3326 "use one::{\n two::three::\n four::five\n};"
3327 );
3328
3329 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
3330 .unwrap();
3331
3332 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3333 assert_eq!(
3334 view.selection_ranges(cx),
3335 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
3336 );
3337
3338 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3339 assert_eq!(
3340 view.selection_ranges(cx),
3341 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3342 );
3343
3344 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3345 assert_eq!(
3346 view.selection_ranges(cx),
3347 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3348 );
3349
3350 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3351 assert_eq!(
3352 view.selection_ranges(cx),
3353 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
3354 );
3355
3356 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3357 assert_eq!(
3358 view.selection_ranges(cx),
3359 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3360 );
3361
3362 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3363 assert_eq!(
3364 view.selection_ranges(cx),
3365 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3366 );
3367 });
3368 }
3369
3370 #[gpui::test]
3371 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
3372 let buffer = cx.add_model(|cx| Buffer::new(0, "one two three four", cx));
3373 let settings = EditorSettings::test(&cx);
3374 let (_, view) = cx.add_window(Default::default(), |cx| {
3375 build_editor(buffer.clone(), settings, cx)
3376 });
3377
3378 view.update(cx, |view, cx| {
3379 view.select_display_ranges(
3380 &[
3381 // an empty selection - the preceding word fragment is deleted
3382 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3383 // characters selected - they are deleted
3384 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
3385 ],
3386 cx,
3387 )
3388 .unwrap();
3389 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
3390 });
3391
3392 assert_eq!(buffer.read(cx).text(), "e two te four");
3393
3394 view.update(cx, |view, cx| {
3395 view.select_display_ranges(
3396 &[
3397 // an empty selection - the following word fragment is deleted
3398 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3399 // characters selected - they are deleted
3400 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
3401 ],
3402 cx,
3403 )
3404 .unwrap();
3405 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
3406 });
3407
3408 assert_eq!(buffer.read(cx).text(), "e t te our");
3409 }
3410
3411 #[gpui::test]
3412 fn test_backspace(cx: &mut gpui::MutableAppContext) {
3413 let buffer = cx.add_model(|cx| {
3414 Buffer::new(
3415 0,
3416 "one two three\nfour five six\nseven eight nine\nten\n",
3417 cx,
3418 )
3419 });
3420 let settings = EditorSettings::test(&cx);
3421 let (_, view) = cx.add_window(Default::default(), |cx| {
3422 build_editor(buffer.clone(), settings, cx)
3423 });
3424
3425 view.update(cx, |view, cx| {
3426 view.select_display_ranges(
3427 &[
3428 // an empty selection - the preceding character is deleted
3429 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3430 // one character selected - it is deleted
3431 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3432 // a line suffix selected - it is deleted
3433 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3434 ],
3435 cx,
3436 )
3437 .unwrap();
3438 view.backspace(&Backspace, cx);
3439 });
3440
3441 assert_eq!(
3442 buffer.read(cx).text(),
3443 "oe two three\nfou five six\nseven ten\n"
3444 );
3445 }
3446
3447 #[gpui::test]
3448 fn test_delete(cx: &mut gpui::MutableAppContext) {
3449 let buffer = cx.add_model(|cx| {
3450 Buffer::new(
3451 0,
3452 "one two three\nfour five six\nseven eight nine\nten\n",
3453 cx,
3454 )
3455 });
3456 let settings = EditorSettings::test(&cx);
3457 let (_, view) = cx.add_window(Default::default(), |cx| {
3458 build_editor(buffer.clone(), settings, cx)
3459 });
3460
3461 view.update(cx, |view, cx| {
3462 view.select_display_ranges(
3463 &[
3464 // an empty selection - the following character is deleted
3465 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3466 // one character selected - it is deleted
3467 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3468 // a line suffix selected - it is deleted
3469 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3470 ],
3471 cx,
3472 )
3473 .unwrap();
3474 view.delete(&Delete, cx);
3475 });
3476
3477 assert_eq!(
3478 buffer.read(cx).text(),
3479 "on two three\nfou five six\nseven ten\n"
3480 );
3481 }
3482
3483 #[gpui::test]
3484 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
3485 let settings = EditorSettings::test(&cx);
3486 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3487 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3488 view.update(cx, |view, cx| {
3489 view.select_display_ranges(
3490 &[
3491 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3492 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
3493 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3494 ],
3495 cx,
3496 )
3497 .unwrap();
3498 view.delete_line(&DeleteLine, cx);
3499 assert_eq!(view.display_text(cx), "ghi");
3500 assert_eq!(
3501 view.selection_ranges(cx),
3502 vec![
3503 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3504 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
3505 ]
3506 );
3507 });
3508
3509 let settings = EditorSettings::test(&cx);
3510 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3511 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3512 view.update(cx, |view, cx| {
3513 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
3514 .unwrap();
3515 view.delete_line(&DeleteLine, cx);
3516 assert_eq!(view.display_text(cx), "ghi\n");
3517 assert_eq!(
3518 view.selection_ranges(cx),
3519 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
3520 );
3521 });
3522 }
3523
3524 #[gpui::test]
3525 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
3526 let settings = EditorSettings::test(&cx);
3527 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3528 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3529 view.update(cx, |view, cx| {
3530 view.select_display_ranges(
3531 &[
3532 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
3533 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3534 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3535 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3536 ],
3537 cx,
3538 )
3539 .unwrap();
3540 view.duplicate_line(&DuplicateLine, cx);
3541 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
3542 assert_eq!(
3543 view.selection_ranges(cx),
3544 vec![
3545 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
3546 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3547 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3548 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
3549 ]
3550 );
3551 });
3552
3553 let settings = EditorSettings::test(&cx);
3554 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
3555 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3556 view.update(cx, |view, cx| {
3557 view.select_display_ranges(
3558 &[
3559 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
3560 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
3561 ],
3562 cx,
3563 )
3564 .unwrap();
3565 view.duplicate_line(&DuplicateLine, cx);
3566 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
3567 assert_eq!(
3568 view.selection_ranges(cx),
3569 vec![
3570 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
3571 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
3572 ]
3573 );
3574 });
3575 }
3576
3577 #[gpui::test]
3578 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
3579 let settings = EditorSettings::test(&cx);
3580 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(10, 5), cx));
3581 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3582 view.update(cx, |view, cx| {
3583 view.fold_ranges(
3584 vec![
3585 Point::new(0, 2)..Point::new(1, 2),
3586 Point::new(2, 3)..Point::new(4, 1),
3587 Point::new(7, 0)..Point::new(8, 4),
3588 ],
3589 cx,
3590 );
3591 view.select_display_ranges(
3592 &[
3593 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3594 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3595 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3596 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
3597 ],
3598 cx,
3599 )
3600 .unwrap();
3601 assert_eq!(
3602 view.display_text(cx),
3603 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
3604 );
3605
3606 view.move_line_up(&MoveLineUp, cx);
3607 assert_eq!(
3608 view.display_text(cx),
3609 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
3610 );
3611 assert_eq!(
3612 view.selection_ranges(cx),
3613 vec![
3614 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3615 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3616 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
3617 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
3618 ]
3619 );
3620 });
3621
3622 view.update(cx, |view, cx| {
3623 view.move_line_down(&MoveLineDown, cx);
3624 assert_eq!(
3625 view.display_text(cx),
3626 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
3627 );
3628 assert_eq!(
3629 view.selection_ranges(cx),
3630 vec![
3631 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3632 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3633 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3634 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
3635 ]
3636 );
3637 });
3638
3639 view.update(cx, |view, cx| {
3640 view.move_line_down(&MoveLineDown, cx);
3641 assert_eq!(
3642 view.display_text(cx),
3643 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
3644 );
3645 assert_eq!(
3646 view.selection_ranges(cx),
3647 vec![
3648 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3649 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
3650 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
3651 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
3652 ]
3653 );
3654 });
3655
3656 view.update(cx, |view, cx| {
3657 view.move_line_up(&MoveLineUp, cx);
3658 assert_eq!(
3659 view.display_text(cx),
3660 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
3661 );
3662 assert_eq!(
3663 view.selection_ranges(cx),
3664 vec![
3665 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3666 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3667 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
3668 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
3669 ]
3670 );
3671 });
3672 }
3673
3674 #[gpui::test]
3675 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
3676 let buffer = cx.add_model(|cx| Buffer::new(0, "one✅ two three four five six ", cx));
3677 let settings = EditorSettings::test(&cx);
3678 let view = cx
3679 .add_window(Default::default(), |cx| {
3680 build_editor(buffer.clone(), settings, cx)
3681 })
3682 .1;
3683
3684 // Cut with three selections. Clipboard text is divided into three slices.
3685 view.update(cx, |view, cx| {
3686 view.select_ranges(vec![0..7, 11..17, 22..27], false, cx);
3687 view.cut(&Cut, cx);
3688 assert_eq!(view.display_text(cx), "two four six ");
3689 });
3690
3691 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
3692 view.update(cx, |view, cx| {
3693 view.select_ranges(vec![4..4, 9..9, 13..13], false, cx);
3694 view.paste(&Paste, cx);
3695 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
3696 assert_eq!(
3697 view.selection_ranges(cx),
3698 &[
3699 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
3700 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
3701 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
3702 ]
3703 );
3704 });
3705
3706 // Paste again but with only two cursors. Since the number of cursors doesn't
3707 // match the number of slices in the clipboard, the entire clipboard text
3708 // is pasted at each cursor.
3709 view.update(cx, |view, cx| {
3710 view.select_ranges(vec![0..0, 31..31], false, cx);
3711 view.insert(&Insert("( ".into()), cx);
3712 view.paste(&Paste, cx);
3713 view.insert(&Insert(") ".into()), cx);
3714 assert_eq!(
3715 view.display_text(cx),
3716 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
3717 );
3718 });
3719
3720 view.update(cx, |view, cx| {
3721 view.select_ranges(vec![0..0], false, cx);
3722 view.insert(&Insert("123\n4567\n89\n".into()), cx);
3723 assert_eq!(
3724 view.display_text(cx),
3725 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
3726 );
3727 });
3728
3729 // Cut with three selections, one of which is full-line.
3730 view.update(cx, |view, cx| {
3731 view.select_display_ranges(
3732 &[
3733 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
3734 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3735 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
3736 ],
3737 cx,
3738 )
3739 .unwrap();
3740 view.cut(&Cut, cx);
3741 assert_eq!(
3742 view.display_text(cx),
3743 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
3744 );
3745 });
3746
3747 // Paste with three selections, noticing how the copied selection that was full-line
3748 // gets inserted before the second cursor.
3749 view.update(cx, |view, cx| {
3750 view.select_display_ranges(
3751 &[
3752 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3753 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3754 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
3755 ],
3756 cx,
3757 )
3758 .unwrap();
3759 view.paste(&Paste, cx);
3760 assert_eq!(
3761 view.display_text(cx),
3762 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
3763 );
3764 assert_eq!(
3765 view.selection_ranges(cx),
3766 &[
3767 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3768 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3769 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
3770 ]
3771 );
3772 });
3773
3774 // Copy with a single cursor only, which writes the whole line into the clipboard.
3775 view.update(cx, |view, cx| {
3776 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
3777 .unwrap();
3778 view.copy(&Copy, cx);
3779 });
3780
3781 // Paste with three selections, noticing how the copied full-line selection is inserted
3782 // before the empty selections but replaces the selection that is non-empty.
3783 view.update(cx, |view, cx| {
3784 view.select_display_ranges(
3785 &[
3786 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3787 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
3788 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
3789 ],
3790 cx,
3791 )
3792 .unwrap();
3793 view.paste(&Paste, cx);
3794 assert_eq!(
3795 view.display_text(cx),
3796 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
3797 );
3798 assert_eq!(
3799 view.selection_ranges(cx),
3800 &[
3801 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
3802 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
3803 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
3804 ]
3805 );
3806 });
3807 }
3808
3809 #[gpui::test]
3810 fn test_select_all(cx: &mut gpui::MutableAppContext) {
3811 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\nde\nfgh", cx));
3812 let settings = EditorSettings::test(&cx);
3813 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3814 view.update(cx, |view, cx| {
3815 view.select_all(&SelectAll, cx);
3816 assert_eq!(
3817 view.selection_ranges(cx),
3818 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
3819 );
3820 });
3821 }
3822
3823 #[gpui::test]
3824 fn test_select_line(cx: &mut gpui::MutableAppContext) {
3825 let settings = EditorSettings::test(&cx);
3826 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 5), cx));
3827 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3828 view.update(cx, |view, cx| {
3829 view.select_display_ranges(
3830 &[
3831 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
3832 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3833 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3834 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
3835 ],
3836 cx,
3837 )
3838 .unwrap();
3839 view.select_line(&SelectLine, cx);
3840 assert_eq!(
3841 view.selection_ranges(cx),
3842 vec![
3843 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
3844 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
3845 ]
3846 );
3847 });
3848
3849 view.update(cx, |view, cx| {
3850 view.select_line(&SelectLine, cx);
3851 assert_eq!(
3852 view.selection_ranges(cx),
3853 vec![
3854 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
3855 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
3856 ]
3857 );
3858 });
3859
3860 view.update(cx, |view, cx| {
3861 view.select_line(&SelectLine, cx);
3862 assert_eq!(
3863 view.selection_ranges(cx),
3864 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
3865 );
3866 });
3867 }
3868
3869 #[gpui::test]
3870 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
3871 let settings = EditorSettings::test(&cx);
3872 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(9, 5), cx));
3873 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3874 view.update(cx, |view, cx| {
3875 view.fold_ranges(
3876 vec![
3877 Point::new(0, 2)..Point::new(1, 2),
3878 Point::new(2, 3)..Point::new(4, 1),
3879 Point::new(7, 0)..Point::new(8, 4),
3880 ],
3881 cx,
3882 );
3883 view.select_display_ranges(
3884 &[
3885 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
3886 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3887 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3888 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
3889 ],
3890 cx,
3891 )
3892 .unwrap();
3893 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
3894 });
3895
3896 view.update(cx, |view, cx| {
3897 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
3898 assert_eq!(
3899 view.display_text(cx),
3900 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
3901 );
3902 assert_eq!(
3903 view.selection_ranges(cx),
3904 [
3905 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3906 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3907 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
3908 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
3909 ]
3910 );
3911 });
3912
3913 view.update(cx, |view, cx| {
3914 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
3915 .unwrap();
3916 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
3917 assert_eq!(
3918 view.display_text(cx),
3919 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
3920 );
3921 assert_eq!(
3922 view.selection_ranges(cx),
3923 [
3924 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3925 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3926 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
3927 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
3928 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
3929 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
3930 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
3931 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
3932 ]
3933 );
3934 });
3935 }
3936
3937 #[gpui::test]
3938 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
3939 let settings = EditorSettings::test(&cx);
3940 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefghi\n\njk\nlmno\n", cx));
3941 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3942
3943 view.update(cx, |view, cx| {
3944 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
3945 .unwrap();
3946 });
3947 view.update(cx, |view, cx| {
3948 view.add_selection_above(&AddSelectionAbove, cx);
3949 assert_eq!(
3950 view.selection_ranges(cx),
3951 vec![
3952 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3953 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
3954 ]
3955 );
3956 });
3957
3958 view.update(cx, |view, cx| {
3959 view.add_selection_above(&AddSelectionAbove, cx);
3960 assert_eq!(
3961 view.selection_ranges(cx),
3962 vec![
3963 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3964 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
3965 ]
3966 );
3967 });
3968
3969 view.update(cx, |view, cx| {
3970 view.add_selection_below(&AddSelectionBelow, cx);
3971 assert_eq!(
3972 view.selection_ranges(cx),
3973 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
3974 );
3975 });
3976
3977 view.update(cx, |view, cx| {
3978 view.add_selection_below(&AddSelectionBelow, cx);
3979 assert_eq!(
3980 view.selection_ranges(cx),
3981 vec![
3982 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
3983 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
3984 ]
3985 );
3986 });
3987
3988 view.update(cx, |view, cx| {
3989 view.add_selection_below(&AddSelectionBelow, cx);
3990 assert_eq!(
3991 view.selection_ranges(cx),
3992 vec![
3993 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
3994 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
3995 ]
3996 );
3997 });
3998
3999 view.update(cx, |view, cx| {
4000 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
4001 .unwrap();
4002 });
4003 view.update(cx, |view, cx| {
4004 view.add_selection_below(&AddSelectionBelow, cx);
4005 assert_eq!(
4006 view.selection_ranges(cx),
4007 vec![
4008 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4009 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4010 ]
4011 );
4012 });
4013
4014 view.update(cx, |view, cx| {
4015 view.add_selection_below(&AddSelectionBelow, cx);
4016 assert_eq!(
4017 view.selection_ranges(cx),
4018 vec![
4019 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4020 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4021 ]
4022 );
4023 });
4024
4025 view.update(cx, |view, cx| {
4026 view.add_selection_above(&AddSelectionAbove, cx);
4027 assert_eq!(
4028 view.selection_ranges(cx),
4029 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4030 );
4031 });
4032
4033 view.update(cx, |view, cx| {
4034 view.add_selection_above(&AddSelectionAbove, cx);
4035 assert_eq!(
4036 view.selection_ranges(cx),
4037 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4038 );
4039 });
4040
4041 view.update(cx, |view, cx| {
4042 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
4043 .unwrap();
4044 view.add_selection_below(&AddSelectionBelow, cx);
4045 assert_eq!(
4046 view.selection_ranges(cx),
4047 vec![
4048 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4049 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4050 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4051 ]
4052 );
4053 });
4054
4055 view.update(cx, |view, cx| {
4056 view.add_selection_below(&AddSelectionBelow, cx);
4057 assert_eq!(
4058 view.selection_ranges(cx),
4059 vec![
4060 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4061 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4062 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4063 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
4064 ]
4065 );
4066 });
4067
4068 view.update(cx, |view, cx| {
4069 view.add_selection_above(&AddSelectionAbove, cx);
4070 assert_eq!(
4071 view.selection_ranges(cx),
4072 vec![
4073 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4074 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4075 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4076 ]
4077 );
4078 });
4079
4080 view.update(cx, |view, cx| {
4081 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
4082 .unwrap();
4083 });
4084 view.update(cx, |view, cx| {
4085 view.add_selection_above(&AddSelectionAbove, cx);
4086 assert_eq!(
4087 view.selection_ranges(cx),
4088 vec![
4089 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
4090 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4091 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4092 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4093 ]
4094 );
4095 });
4096
4097 view.update(cx, |view, cx| {
4098 view.add_selection_below(&AddSelectionBelow, cx);
4099 assert_eq!(
4100 view.selection_ranges(cx),
4101 vec![
4102 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4103 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4104 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4105 ]
4106 );
4107 });
4108 }
4109
4110 #[gpui::test]
4111 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
4112 let settings = cx.read(EditorSettings::test);
4113 let language = Arc::new(Language::new(
4114 LanguageConfig::default(),
4115 tree_sitter_rust::language(),
4116 ));
4117
4118 let text = r#"
4119 use mod1::mod2::{mod3, mod4};
4120
4121 fn fn_1(param1: bool, param2: &str) {
4122 let var1 = "text";
4123 }
4124 "#
4125 .unindent();
4126
4127 let buffer = cx.add_model(|cx| {
4128 let history = History::new(text.into());
4129 Buffer::from_history(0, history, None, Some(language), cx)
4130 });
4131 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4132 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4133 .await;
4134
4135 view.update(&mut cx, |view, cx| {
4136 view.select_display_ranges(
4137 &[
4138 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4139 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4140 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4141 ],
4142 cx,
4143 )
4144 .unwrap();
4145 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4146 });
4147 assert_eq!(
4148 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4149 &[
4150 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4151 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4152 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4153 ]
4154 );
4155
4156 view.update(&mut cx, |view, cx| {
4157 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4158 });
4159 assert_eq!(
4160 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4161 &[
4162 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4163 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4164 ]
4165 );
4166
4167 view.update(&mut cx, |view, cx| {
4168 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4169 });
4170 assert_eq!(
4171 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4172 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4173 );
4174
4175 // Trying to expand the selected syntax node one more time has no effect.
4176 view.update(&mut cx, |view, cx| {
4177 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4178 });
4179 assert_eq!(
4180 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4181 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4182 );
4183
4184 view.update(&mut cx, |view, cx| {
4185 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4186 });
4187 assert_eq!(
4188 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4189 &[
4190 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4191 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4192 ]
4193 );
4194
4195 view.update(&mut cx, |view, cx| {
4196 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4197 });
4198 assert_eq!(
4199 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4200 &[
4201 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4202 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4203 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4204 ]
4205 );
4206
4207 view.update(&mut cx, |view, cx| {
4208 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4209 });
4210 assert_eq!(
4211 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4212 &[
4213 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4214 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4215 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4216 ]
4217 );
4218
4219 // Trying to shrink the selected syntax node one more time has no effect.
4220 view.update(&mut cx, |view, cx| {
4221 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4222 });
4223 assert_eq!(
4224 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4225 &[
4226 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4227 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4228 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4229 ]
4230 );
4231
4232 // Ensure that we keep expanding the selection if the larger selection starts or ends within
4233 // a fold.
4234 view.update(&mut cx, |view, cx| {
4235 view.fold_ranges(
4236 vec![
4237 Point::new(0, 21)..Point::new(0, 24),
4238 Point::new(3, 20)..Point::new(3, 22),
4239 ],
4240 cx,
4241 );
4242 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4243 });
4244 assert_eq!(
4245 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4246 &[
4247 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4248 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4249 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
4250 ]
4251 );
4252 }
4253
4254 #[gpui::test]
4255 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
4256 let settings = cx.read(EditorSettings::test);
4257 let language = Arc::new(Language::new(
4258 LanguageConfig {
4259 autoclose_pairs: vec![
4260 AutoclosePair {
4261 start: "{".to_string(),
4262 end: "}".to_string(),
4263 },
4264 AutoclosePair {
4265 start: "/*".to_string(),
4266 end: " */".to_string(),
4267 },
4268 ],
4269 ..Default::default()
4270 },
4271 tree_sitter_rust::language(),
4272 ));
4273
4274 let text = r#"
4275 a
4276
4277 /
4278
4279 "#
4280 .unindent();
4281
4282 let buffer = cx.add_model(|cx| {
4283 let history = History::new(text.into());
4284 Buffer::from_history(0, history, None, Some(language), cx)
4285 });
4286 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4287 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4288 .await;
4289
4290 view.update(&mut cx, |view, cx| {
4291 view.select_display_ranges(
4292 &[
4293 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4294 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4295 ],
4296 cx,
4297 )
4298 .unwrap();
4299 view.insert(&Insert("{".to_string()), cx);
4300 assert_eq!(
4301 view.text(cx),
4302 "
4303 {}
4304 {}
4305 /
4306
4307 "
4308 .unindent()
4309 );
4310
4311 view.undo(&Undo, cx);
4312 view.insert(&Insert("/".to_string()), cx);
4313 view.insert(&Insert("*".to_string()), cx);
4314 assert_eq!(
4315 view.text(cx),
4316 "
4317 /* */
4318 /* */
4319 /
4320
4321 "
4322 .unindent()
4323 );
4324
4325 view.undo(&Undo, cx);
4326 view.select_display_ranges(
4327 &[
4328 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4329 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4330 ],
4331 cx,
4332 )
4333 .unwrap();
4334 view.insert(&Insert("*".to_string()), cx);
4335 assert_eq!(
4336 view.text(cx),
4337 "
4338 a
4339
4340 /*
4341 *
4342 "
4343 .unindent()
4344 );
4345 });
4346 }
4347
4348 impl Editor {
4349 fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
4350 self.selections_in_range(
4351 self.selection_set_id,
4352 DisplayPoint::zero()..self.max_point(cx),
4353 cx,
4354 )
4355 .collect::<Vec<_>>()
4356 }
4357 }
4358
4359 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
4360 let point = DisplayPoint::new(row as u32, column as u32);
4361 point..point
4362 }
4363
4364 fn build_editor(
4365 buffer: ModelHandle<Buffer>,
4366 settings: EditorSettings,
4367 cx: &mut ViewContext<Editor>,
4368 ) -> Editor {
4369 Editor::for_buffer(buffer, move |_| settings.clone(), cx)
4370 }
4371}
4372
4373trait RangeExt<T> {
4374 fn sorted(&self) -> Range<T>;
4375 fn to_inclusive(&self) -> RangeInclusive<T>;
4376}
4377
4378impl<T: Ord + Clone> RangeExt<T> for Range<T> {
4379 fn sorted(&self) -> Self {
4380 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
4381 }
4382
4383 fn to_inclusive(&self) -> RangeInclusive<T> {
4384 self.start.clone()..=self.end.clone()
4385 }
4386}