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