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