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