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