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