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