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