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