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