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