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