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