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