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 intersecting_selections<'a>(
3021 &'a self,
3022 set_id: SelectionSetId,
3023 range: Range<DisplayPoint>,
3024 cx: &'a mut MutableAppContext,
3025 ) -> impl 'a + Iterator<Item = Selection<DisplayPoint>> {
3026 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3027 let buffer = self.buffer.read(cx);
3028
3029 let pending_selection = if set_id == self.selection_set_id {
3030 self.pending_selection.as_ref().and_then(|pending| {
3031 let selection_start = pending.selection.start.to_display_point(&display_map);
3032 let selection_end = pending.selection.end.to_display_point(&display_map);
3033 if selection_start <= range.end || selection_end <= range.end {
3034 Some(Selection {
3035 id: pending.selection.id,
3036 start: selection_start,
3037 end: selection_end,
3038 reversed: pending.selection.reversed,
3039 goal: pending.selection.goal,
3040 })
3041 } else {
3042 None
3043 }
3044 })
3045 } else {
3046 None
3047 };
3048
3049 let range = (range.start.to_offset(&display_map, Bias::Left), Bias::Left)
3050 ..(range.end.to_offset(&display_map, Bias::Left), Bias::Right);
3051 let selections = self
3052 .buffer
3053 .read(cx)
3054 .selection_set(set_id)
3055 .unwrap()
3056 .intersecting_selections::<Point, _, _>(range, buffer);
3057
3058 selections
3059 .map(move |s| Selection {
3060 id: s.id,
3061 start: s.start.to_display_point(&display_map),
3062 end: s.end.to_display_point(&display_map),
3063 reversed: s.reversed,
3064 goal: s.goal,
3065 })
3066 .chain(pending_selection)
3067 }
3068
3069 pub fn selections<'a, D>(&self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Selection<D>>
3070 where
3071 D: 'a + TextDimension<'a> + Ord,
3072 {
3073 let buffer = self.buffer.read(cx);
3074 let mut selections = self.selection_set(cx).selections::<D, _>(buffer).peekable();
3075 let mut pending_selection = self.pending_selection(cx);
3076 iter::from_fn(move || {
3077 if let Some(pending) = pending_selection.as_mut() {
3078 while let Some(next_selection) = selections.peek() {
3079 if pending.start <= next_selection.end && pending.end >= next_selection.start {
3080 let next_selection = selections.next().unwrap();
3081 if next_selection.start < pending.start {
3082 pending.start = next_selection.start;
3083 }
3084 if next_selection.end > pending.end {
3085 pending.end = next_selection.end;
3086 }
3087 } else if next_selection.end < pending.start {
3088 return selections.next();
3089 } else {
3090 break;
3091 }
3092 }
3093
3094 pending_selection.take()
3095 } else {
3096 selections.next()
3097 }
3098 })
3099 }
3100
3101 fn pending_selection<'a, D>(&self, cx: &'a AppContext) -> Option<Selection<D>>
3102 where
3103 D: 'a + TextDimension<'a>,
3104 {
3105 let buffer = self.buffer.read(cx);
3106 self.pending_selection.as_ref().map(|pending| Selection {
3107 id: pending.selection.id,
3108 start: pending.selection.start.summary::<D, _>(buffer),
3109 end: pending.selection.end.summary::<D, _>(buffer),
3110 reversed: pending.selection.reversed,
3111 goal: pending.selection.goal,
3112 })
3113 }
3114
3115 fn selection_count<'a>(&self, cx: &'a AppContext) -> usize {
3116 let mut selection_count = self.selection_set(cx).len();
3117 if self.pending_selection.is_some() {
3118 selection_count += 1;
3119 }
3120 selection_count
3121 }
3122
3123 pub fn oldest_selection<'a, T>(&self, cx: &'a AppContext) -> Selection<T>
3124 where
3125 T: 'a + TextDimension<'a>,
3126 {
3127 let buffer = self.buffer.read(cx);
3128 self.selection_set(cx)
3129 .oldest_selection(buffer)
3130 .or_else(|| self.pending_selection(cx))
3131 .unwrap()
3132 }
3133
3134 pub fn newest_selection<'a, T>(&self, cx: &'a AppContext) -> Selection<T>
3135 where
3136 T: 'a + TextDimension<'a>,
3137 {
3138 let buffer = self.buffer.read(cx);
3139 self.pending_selection(cx)
3140 .or_else(|| self.selection_set(cx).newest_selection(buffer))
3141 .unwrap()
3142 }
3143
3144 fn selection_set<'a>(&self, cx: &'a AppContext) -> &'a SelectionSet {
3145 self.buffer
3146 .read(cx)
3147 .selection_set(self.selection_set_id)
3148 .unwrap()
3149 }
3150
3151 pub fn update_selections<T>(
3152 &mut self,
3153 mut selections: Vec<Selection<T>>,
3154 autoscroll: Option<Autoscroll>,
3155 cx: &mut ViewContext<Self>,
3156 ) where
3157 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3158 {
3159 // Merge overlapping selections.
3160 let buffer = self.buffer.read(cx);
3161 let mut i = 1;
3162 while i < selections.len() {
3163 if selections[i - 1].end >= selections[i].start {
3164 let removed = selections.remove(i);
3165 if removed.start < selections[i - 1].start {
3166 selections[i - 1].start = removed.start;
3167 }
3168 if removed.end > selections[i - 1].end {
3169 selections[i - 1].end = removed.end;
3170 }
3171 } else {
3172 i += 1;
3173 }
3174 }
3175
3176 self.pending_selection = None;
3177 self.add_selections_state = None;
3178 self.select_next_state = None;
3179 self.select_larger_syntax_node_stack.clear();
3180 while let Some(autoclose_pair_state) = self.autoclose_stack.last() {
3181 let all_selections_inside_autoclose_ranges =
3182 if selections.len() == autoclose_pair_state.ranges.len() {
3183 selections
3184 .iter()
3185 .zip(autoclose_pair_state.ranges.ranges::<Point, _>(buffer))
3186 .all(|(selection, autoclose_range)| {
3187 let head = selection.head().to_point(&*buffer);
3188 autoclose_range.start <= head && autoclose_range.end >= head
3189 })
3190 } else {
3191 false
3192 };
3193
3194 if all_selections_inside_autoclose_ranges {
3195 break;
3196 } else {
3197 self.autoclose_stack.pop();
3198 }
3199 }
3200
3201 if let Some(autoscroll) = autoscroll {
3202 self.request_autoscroll(autoscroll, cx);
3203 }
3204 self.pause_cursor_blinking(cx);
3205
3206 self.buffer.update(cx, |buffer, cx| {
3207 buffer
3208 .update_selection_set(self.selection_set_id, &selections, cx)
3209 .unwrap();
3210 });
3211 }
3212
3213 fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3214 self.autoscroll_request = Some(autoscroll);
3215 cx.notify();
3216 }
3217
3218 fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3219 self.end_selection(cx);
3220 self.buffer.update(cx, |buffer, _| {
3221 buffer
3222 .start_transaction(Some(self.selection_set_id))
3223 .unwrap()
3224 });
3225 }
3226
3227 fn end_transaction(&self, cx: &mut ViewContext<Self>) {
3228 self.buffer.update(cx, |buffer, cx| {
3229 buffer
3230 .end_transaction(Some(self.selection_set_id), cx)
3231 .unwrap()
3232 });
3233 }
3234
3235 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3236 log::info!("Editor::page_up");
3237 }
3238
3239 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3240 log::info!("Editor::page_down");
3241 }
3242
3243 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3244 let mut fold_ranges = Vec::new();
3245
3246 let selections = self.selections::<Point>(cx).collect::<Vec<_>>();
3247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3248 for selection in selections {
3249 let range = selection.display_range(&display_map).sorted();
3250 let buffer_start_row = range.start.to_point(&display_map).row;
3251
3252 for row in (0..=range.end.row()).rev() {
3253 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3254 let fold_range = self.foldable_range_for_line(&display_map, row);
3255 if fold_range.end.row >= buffer_start_row {
3256 fold_ranges.push(fold_range);
3257 if row <= range.start.row() {
3258 break;
3259 }
3260 }
3261 }
3262 }
3263 }
3264
3265 self.fold_ranges(fold_ranges, cx);
3266 }
3267
3268 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3269 let selections = self.selections::<Point>(cx).collect::<Vec<_>>();
3270 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3271 let buffer = self.buffer.read(cx);
3272 let ranges = selections
3273 .iter()
3274 .map(|s| {
3275 let range = s.display_range(&display_map).sorted();
3276 let mut start = range.start.to_point(&display_map);
3277 let mut end = range.end.to_point(&display_map);
3278 start.column = 0;
3279 end.column = buffer.line_len(end.row);
3280 start..end
3281 })
3282 .collect::<Vec<_>>();
3283 self.unfold_ranges(ranges, cx);
3284 }
3285
3286 fn is_line_foldable(&self, display_map: &DisplayMapSnapshot, display_row: u32) -> bool {
3287 let max_point = display_map.max_point();
3288 if display_row >= max_point.row() {
3289 false
3290 } else {
3291 let (start_indent, is_blank) = display_map.line_indent(display_row);
3292 if is_blank {
3293 false
3294 } else {
3295 for display_row in display_row + 1..=max_point.row() {
3296 let (indent, is_blank) = display_map.line_indent(display_row);
3297 if !is_blank {
3298 return indent > start_indent;
3299 }
3300 }
3301 false
3302 }
3303 }
3304 }
3305
3306 fn foldable_range_for_line(
3307 &self,
3308 display_map: &DisplayMapSnapshot,
3309 start_row: u32,
3310 ) -> Range<Point> {
3311 let max_point = display_map.max_point();
3312
3313 let (start_indent, _) = display_map.line_indent(start_row);
3314 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3315 let mut end = None;
3316 for row in start_row + 1..=max_point.row() {
3317 let (indent, is_blank) = display_map.line_indent(row);
3318 if !is_blank && indent <= start_indent {
3319 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3320 break;
3321 }
3322 }
3323
3324 let end = end.unwrap_or(max_point);
3325 return start.to_point(display_map)..end.to_point(display_map);
3326 }
3327
3328 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3329 let selections = self.selections::<Point>(cx);
3330 let ranges = selections.map(|s| s.start..s.end).collect();
3331 self.fold_ranges(ranges, cx);
3332 }
3333
3334 fn fold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3335 if !ranges.is_empty() {
3336 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3337 self.request_autoscroll(Autoscroll::Fit, cx);
3338 cx.notify();
3339 }
3340 }
3341
3342 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3343 if !ranges.is_empty() {
3344 self.display_map
3345 .update(cx, |map, cx| map.unfold(ranges, cx));
3346 self.request_autoscroll(Autoscroll::Fit, cx);
3347 cx.notify();
3348 }
3349 }
3350
3351 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3352 self.display_map
3353 .update(cx, |map, cx| map.snapshot(cx))
3354 .longest_row()
3355 }
3356
3357 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3358 self.display_map
3359 .update(cx, |map, cx| map.snapshot(cx))
3360 .max_point()
3361 }
3362
3363 pub fn text(&self, cx: &AppContext) -> String {
3364 self.buffer.read(cx).text()
3365 }
3366
3367 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3368 self.display_map
3369 .update(cx, |map, cx| map.snapshot(cx))
3370 .text()
3371 }
3372
3373 pub fn set_wrap_width(&self, width: f32, cx: &mut MutableAppContext) -> bool {
3374 self.display_map
3375 .update(cx, |map, cx| map.set_wrap_width(Some(width), cx))
3376 }
3377
3378 pub fn set_highlighted_row(&mut self, row: Option<u32>) {
3379 self.highlighted_row = row;
3380 }
3381
3382 pub fn highlighted_row(&mut self) -> Option<u32> {
3383 self.highlighted_row
3384 }
3385
3386 fn next_blink_epoch(&mut self) -> usize {
3387 self.blink_epoch += 1;
3388 self.blink_epoch
3389 }
3390
3391 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3392 self.show_local_cursors = true;
3393 cx.notify();
3394
3395 let epoch = self.next_blink_epoch();
3396 cx.spawn(|this, mut cx| {
3397 let this = this.downgrade();
3398 async move {
3399 Timer::after(CURSOR_BLINK_INTERVAL).await;
3400 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3401 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3402 }
3403 }
3404 })
3405 .detach();
3406 }
3407
3408 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3409 if epoch == self.blink_epoch {
3410 self.blinking_paused = false;
3411 self.blink_cursors(epoch, cx);
3412 }
3413 }
3414
3415 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3416 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3417 self.show_local_cursors = !self.show_local_cursors;
3418 cx.notify();
3419
3420 let epoch = self.next_blink_epoch();
3421 cx.spawn(|this, mut cx| {
3422 let this = this.downgrade();
3423 async move {
3424 Timer::after(CURSOR_BLINK_INTERVAL).await;
3425 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3426 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3427 }
3428 }
3429 })
3430 .detach();
3431 }
3432 }
3433
3434 pub fn show_local_cursors(&self) -> bool {
3435 self.show_local_cursors
3436 }
3437
3438 fn on_buffer_changed(&mut self, _: ModelHandle<Buffer>, cx: &mut ViewContext<Self>) {
3439 self.refresh_active_diagnostics(cx);
3440 cx.notify();
3441 }
3442
3443 fn on_buffer_event(
3444 &mut self,
3445 _: ModelHandle<Buffer>,
3446 event: &language::Event,
3447 cx: &mut ViewContext<Self>,
3448 ) {
3449 match event {
3450 language::Event::Edited => cx.emit(Event::Edited),
3451 language::Event::Dirtied => cx.emit(Event::Dirtied),
3452 language::Event::Saved => cx.emit(Event::Saved),
3453 language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
3454 language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
3455 language::Event::Closed => cx.emit(Event::Closed),
3456 language::Event::Reparsed => {}
3457 }
3458 }
3459
3460 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3461 cx.notify();
3462 }
3463}
3464
3465impl Snapshot {
3466 pub fn is_empty(&self) -> bool {
3467 self.display_snapshot.is_empty()
3468 }
3469
3470 pub fn is_focused(&self) -> bool {
3471 self.is_focused
3472 }
3473
3474 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3475 self.placeholder_text.as_ref()
3476 }
3477
3478 pub fn buffer_row_count(&self) -> u32 {
3479 self.display_snapshot.buffer_row_count()
3480 }
3481
3482 pub fn buffer_rows<'a>(&'a self, start_row: u32, cx: &'a AppContext) -> BufferRows<'a> {
3483 self.display_snapshot.buffer_rows(start_row, Some(cx))
3484 }
3485
3486 pub fn chunks<'a>(
3487 &'a self,
3488 display_rows: Range<u32>,
3489 theme: Option<&'a SyntaxTheme>,
3490 cx: &'a AppContext,
3491 ) -> display_map::Chunks<'a> {
3492 self.display_snapshot.chunks(display_rows, theme, cx)
3493 }
3494
3495 pub fn scroll_position(&self) -> Vector2F {
3496 compute_scroll_position(
3497 &self.display_snapshot,
3498 self.scroll_position,
3499 &self.scroll_top_anchor,
3500 )
3501 }
3502
3503 pub fn max_point(&self) -> DisplayPoint {
3504 self.display_snapshot.max_point()
3505 }
3506
3507 pub fn longest_row(&self) -> u32 {
3508 self.display_snapshot.longest_row()
3509 }
3510
3511 pub fn line_len(&self, display_row: u32) -> u32 {
3512 self.display_snapshot.line_len(display_row)
3513 }
3514
3515 pub fn line(&self, display_row: u32) -> String {
3516 self.display_snapshot.line(display_row)
3517 }
3518
3519 pub fn prev_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
3520 self.display_snapshot.prev_row_boundary(point)
3521 }
3522
3523 pub fn next_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
3524 self.display_snapshot.next_row_boundary(point)
3525 }
3526}
3527
3528impl EditorSettings {
3529 #[cfg(any(test, feature = "test-support"))]
3530 pub fn test(cx: &AppContext) -> Self {
3531 Self {
3532 tab_size: 4,
3533 style: {
3534 let font_cache: &gpui::FontCache = cx.font_cache();
3535 let font_family_name = Arc::from("Monaco");
3536 let font_properties = Default::default();
3537 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3538 let font_id = font_cache
3539 .select_font(font_family_id, &font_properties)
3540 .unwrap();
3541 EditorStyle {
3542 text: gpui::fonts::TextStyle {
3543 font_family_name,
3544 font_family_id,
3545 font_id,
3546 font_size: 14.,
3547 color: gpui::color::Color::from_u32(0xff0000ff),
3548 font_properties,
3549 underline: None,
3550 },
3551 placeholder_text: None,
3552 background: Default::default(),
3553 gutter_background: Default::default(),
3554 active_line_background: Default::default(),
3555 highlighted_line_background: Default::default(),
3556 line_number: Default::default(),
3557 line_number_active: Default::default(),
3558 selection: Default::default(),
3559 guest_selections: Default::default(),
3560 syntax: Default::default(),
3561 error_diagnostic: Default::default(),
3562 invalid_error_diagnostic: Default::default(),
3563 warning_diagnostic: Default::default(),
3564 invalid_warning_diagnostic: Default::default(),
3565 information_diagnostic: Default::default(),
3566 invalid_information_diagnostic: Default::default(),
3567 hint_diagnostic: Default::default(),
3568 invalid_hint_diagnostic: Default::default(),
3569 }
3570 },
3571 }
3572 }
3573}
3574
3575fn compute_scroll_position(
3576 snapshot: &DisplayMapSnapshot,
3577 mut scroll_position: Vector2F,
3578 scroll_top_anchor: &Anchor,
3579) -> Vector2F {
3580 let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3581 scroll_position.set_y(scroll_top + scroll_position.y());
3582 scroll_position
3583}
3584
3585pub enum Event {
3586 Activate,
3587 Edited,
3588 Blurred,
3589 Dirtied,
3590 Saved,
3591 FileHandleChanged,
3592 Closed,
3593}
3594
3595impl Entity for Editor {
3596 type Event = Event;
3597
3598 fn release(&mut self, cx: &mut MutableAppContext) {
3599 self.buffer.update(cx, |buffer, cx| {
3600 buffer
3601 .remove_selection_set(self.selection_set_id, cx)
3602 .unwrap();
3603 });
3604 }
3605}
3606
3607impl View for Editor {
3608 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3609 let settings = self.build_settings.borrow_mut()(cx);
3610 self.display_map.update(cx, |map, cx| {
3611 map.set_font(
3612 settings.style.text.font_id,
3613 settings.style.text.font_size,
3614 cx,
3615 )
3616 });
3617 EditorElement::new(self.handle.clone(), settings).boxed()
3618 }
3619
3620 fn ui_name() -> &'static str {
3621 "Editor"
3622 }
3623
3624 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3625 self.focused = true;
3626 self.blink_cursors(self.blink_epoch, cx);
3627 self.buffer.update(cx, |buffer, cx| {
3628 buffer
3629 .set_active_selection_set(Some(self.selection_set_id), cx)
3630 .unwrap();
3631 });
3632 }
3633
3634 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3635 self.focused = false;
3636 self.show_local_cursors = false;
3637 self.buffer.update(cx, |buffer, cx| {
3638 buffer.set_active_selection_set(None, cx).unwrap();
3639 });
3640 cx.emit(Event::Blurred);
3641 cx.notify();
3642 }
3643
3644 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3645 let mut cx = Self::default_keymap_context();
3646 let mode = match self.mode {
3647 EditorMode::SingleLine => "single_line",
3648 EditorMode::AutoHeight { .. } => "auto_height",
3649 EditorMode::Full => "full",
3650 };
3651 cx.map.insert("mode".into(), mode.into());
3652 cx
3653 }
3654}
3655
3656impl SelectionExt for Selection<Point> {
3657 fn display_range(&self, map: &DisplayMapSnapshot) -> Range<DisplayPoint> {
3658 let start = self.start.to_display_point(map);
3659 let end = self.end.to_display_point(map);
3660 if self.reversed {
3661 end..start
3662 } else {
3663 start..end
3664 }
3665 }
3666
3667 fn spanned_rows(
3668 &self,
3669 include_end_if_at_line_start: bool,
3670 map: &DisplayMapSnapshot,
3671 ) -> SpannedRows {
3672 let display_start = self.start.to_display_point(map);
3673 let mut display_end = self.end.to_display_point(map);
3674 if !include_end_if_at_line_start
3675 && display_end.row() != map.max_point().row()
3676 && display_start.row() != display_end.row()
3677 && display_end.column() == 0
3678 {
3679 *display_end.row_mut() -= 1;
3680 }
3681
3682 let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3683 let (display_end, buffer_end) = map.next_row_boundary(display_end);
3684
3685 SpannedRows {
3686 buffer_rows: buffer_start.row..buffer_end.row + 1,
3687 display_rows: display_start.row()..display_end.row() + 1,
3688 }
3689 }
3690}
3691
3692pub fn diagnostic_style(
3693 severity: DiagnosticSeverity,
3694 valid: bool,
3695 style: &EditorStyle,
3696) -> DiagnosticStyle {
3697 match (severity, valid) {
3698 (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3699 (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3700 (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3701 (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3702 (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3703 (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3704 (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3705 (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3706 _ => Default::default(),
3707 }
3708}
3709
3710#[cfg(test)]
3711mod tests {
3712 use super::*;
3713 use crate::test::sample_text;
3714 use buffer::Point;
3715 use unindent::Unindent;
3716
3717 #[gpui::test]
3718 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3719 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3720 let settings = EditorSettings::test(cx);
3721 let (_, editor) =
3722 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3723
3724 editor.update(cx, |view, cx| {
3725 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3726 });
3727
3728 assert_eq!(
3729 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3730 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3731 );
3732
3733 editor.update(cx, |view, cx| {
3734 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3735 });
3736
3737 assert_eq!(
3738 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3739 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3740 );
3741
3742 editor.update(cx, |view, cx| {
3743 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3744 });
3745
3746 assert_eq!(
3747 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3748 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3749 );
3750
3751 editor.update(cx, |view, cx| {
3752 view.end_selection(cx);
3753 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3754 });
3755
3756 assert_eq!(
3757 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3758 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3759 );
3760
3761 editor.update(cx, |view, cx| {
3762 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
3763 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
3764 });
3765
3766 assert_eq!(
3767 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3768 [
3769 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3770 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3771 ]
3772 );
3773
3774 editor.update(cx, |view, cx| {
3775 view.end_selection(cx);
3776 });
3777
3778 assert_eq!(
3779 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3780 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3781 );
3782 }
3783
3784 #[gpui::test]
3785 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3786 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3787 let settings = EditorSettings::test(cx);
3788 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3789
3790 view.update(cx, |view, cx| {
3791 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3792 assert_eq!(
3793 view.selection_ranges(cx),
3794 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3795 );
3796 });
3797
3798 view.update(cx, |view, cx| {
3799 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3800 assert_eq!(
3801 view.selection_ranges(cx),
3802 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3803 );
3804 });
3805
3806 view.update(cx, |view, cx| {
3807 view.cancel(&Cancel, cx);
3808 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3809 assert_eq!(
3810 view.selection_ranges(cx),
3811 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3812 );
3813 });
3814 }
3815
3816 #[gpui::test]
3817 fn test_cancel(cx: &mut gpui::MutableAppContext) {
3818 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3819 let settings = EditorSettings::test(cx);
3820 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3821
3822 view.update(cx, |view, cx| {
3823 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
3824 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3825 view.end_selection(cx);
3826
3827 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
3828 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
3829 view.end_selection(cx);
3830 assert_eq!(
3831 view.selection_ranges(cx),
3832 [
3833 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
3834 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
3835 ]
3836 );
3837 });
3838
3839 view.update(cx, |view, cx| {
3840 view.cancel(&Cancel, cx);
3841 assert_eq!(
3842 view.selection_ranges(cx),
3843 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
3844 );
3845 });
3846
3847 view.update(cx, |view, cx| {
3848 view.cancel(&Cancel, cx);
3849 assert_eq!(
3850 view.selection_ranges(cx),
3851 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
3852 );
3853 });
3854 }
3855
3856 #[gpui::test]
3857 fn test_fold(cx: &mut gpui::MutableAppContext) {
3858 let buffer = cx.add_model(|cx| {
3859 Buffer::new(
3860 0,
3861 "
3862 impl Foo {
3863 // Hello!
3864
3865 fn a() {
3866 1
3867 }
3868
3869 fn b() {
3870 2
3871 }
3872
3873 fn c() {
3874 3
3875 }
3876 }
3877 "
3878 .unindent(),
3879 cx,
3880 )
3881 });
3882 let settings = EditorSettings::test(&cx);
3883 let (_, view) = cx.add_window(Default::default(), |cx| {
3884 build_editor(buffer.clone(), settings, cx)
3885 });
3886
3887 view.update(cx, |view, cx| {
3888 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
3889 .unwrap();
3890 view.fold(&Fold, cx);
3891 assert_eq!(
3892 view.display_text(cx),
3893 "
3894 impl Foo {
3895 // Hello!
3896
3897 fn a() {
3898 1
3899 }
3900
3901 fn b() {…
3902 }
3903
3904 fn c() {…
3905 }
3906 }
3907 "
3908 .unindent(),
3909 );
3910
3911 view.fold(&Fold, cx);
3912 assert_eq!(
3913 view.display_text(cx),
3914 "
3915 impl Foo {…
3916 }
3917 "
3918 .unindent(),
3919 );
3920
3921 view.unfold(&Unfold, cx);
3922 assert_eq!(
3923 view.display_text(cx),
3924 "
3925 impl Foo {
3926 // Hello!
3927
3928 fn a() {
3929 1
3930 }
3931
3932 fn b() {…
3933 }
3934
3935 fn c() {…
3936 }
3937 }
3938 "
3939 .unindent(),
3940 );
3941
3942 view.unfold(&Unfold, cx);
3943 assert_eq!(view.display_text(cx), buffer.read(cx).text());
3944 });
3945 }
3946
3947 #[gpui::test]
3948 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
3949 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
3950 let settings = EditorSettings::test(&cx);
3951 let (_, view) = cx.add_window(Default::default(), |cx| {
3952 build_editor(buffer.clone(), settings, cx)
3953 });
3954
3955 buffer.update(cx, |buffer, cx| {
3956 buffer.edit(
3957 vec![
3958 Point::new(1, 0)..Point::new(1, 0),
3959 Point::new(1, 1)..Point::new(1, 1),
3960 ],
3961 "\t",
3962 cx,
3963 );
3964 });
3965
3966 view.update(cx, |view, cx| {
3967 assert_eq!(
3968 view.selection_ranges(cx),
3969 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3970 );
3971
3972 view.move_down(&MoveDown, cx);
3973 assert_eq!(
3974 view.selection_ranges(cx),
3975 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3976 );
3977
3978 view.move_right(&MoveRight, cx);
3979 assert_eq!(
3980 view.selection_ranges(cx),
3981 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3982 );
3983
3984 view.move_left(&MoveLeft, cx);
3985 assert_eq!(
3986 view.selection_ranges(cx),
3987 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3988 );
3989
3990 view.move_up(&MoveUp, cx);
3991 assert_eq!(
3992 view.selection_ranges(cx),
3993 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3994 );
3995
3996 view.move_to_end(&MoveToEnd, cx);
3997 assert_eq!(
3998 view.selection_ranges(cx),
3999 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4000 );
4001
4002 view.move_to_beginning(&MoveToBeginning, cx);
4003 assert_eq!(
4004 view.selection_ranges(cx),
4005 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4006 );
4007
4008 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4009 .unwrap();
4010 view.select_to_beginning(&SelectToBeginning, cx);
4011 assert_eq!(
4012 view.selection_ranges(cx),
4013 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4014 );
4015
4016 view.select_to_end(&SelectToEnd, cx);
4017 assert_eq!(
4018 view.selection_ranges(cx),
4019 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4020 );
4021 });
4022 }
4023
4024 #[gpui::test]
4025 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4026 let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx));
4027 let settings = EditorSettings::test(&cx);
4028 let (_, view) = cx.add_window(Default::default(), |cx| {
4029 build_editor(buffer.clone(), settings, cx)
4030 });
4031
4032 assert_eq!('ⓐ'.len_utf8(), 3);
4033 assert_eq!('α'.len_utf8(), 2);
4034
4035 view.update(cx, |view, cx| {
4036 view.fold_ranges(
4037 vec![
4038 Point::new(0, 6)..Point::new(0, 12),
4039 Point::new(1, 2)..Point::new(1, 4),
4040 Point::new(2, 4)..Point::new(2, 8),
4041 ],
4042 cx,
4043 );
4044 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4045
4046 view.move_right(&MoveRight, cx);
4047 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
4048 view.move_right(&MoveRight, cx);
4049 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4050 view.move_right(&MoveRight, cx);
4051 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4052
4053 view.move_down(&MoveDown, cx);
4054 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
4055 view.move_left(&MoveLeft, cx);
4056 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
4057 view.move_left(&MoveLeft, cx);
4058 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
4059
4060 view.move_down(&MoveDown, cx);
4061 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
4062 view.move_right(&MoveRight, cx);
4063 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
4064 view.move_right(&MoveRight, cx);
4065 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
4066 view.move_right(&MoveRight, cx);
4067 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
4068
4069 view.move_up(&MoveUp, cx);
4070 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
4071 view.move_up(&MoveUp, cx);
4072 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
4073 view.move_left(&MoveLeft, cx);
4074 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4075 view.move_left(&MoveLeft, cx);
4076 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4077 view.move_left(&MoveLeft, cx);
4078 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
4079 });
4080 }
4081
4082 #[gpui::test]
4083 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4084 let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx));
4085 let settings = EditorSettings::test(&cx);
4086 let (_, view) = cx.add_window(Default::default(), |cx| {
4087 build_editor(buffer.clone(), settings, cx)
4088 });
4089 view.update(cx, |view, cx| {
4090 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4091 .unwrap();
4092
4093 view.move_down(&MoveDown, cx);
4094 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
4095
4096 view.move_down(&MoveDown, cx);
4097 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4098
4099 view.move_down(&MoveDown, cx);
4100 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4101
4102 view.move_down(&MoveDown, cx);
4103 assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
4104
4105 view.move_up(&MoveUp, cx);
4106 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4107
4108 view.move_up(&MoveUp, cx);
4109 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4110 });
4111 }
4112
4113 #[gpui::test]
4114 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4115 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\n def", cx));
4116 let settings = EditorSettings::test(&cx);
4117 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4118 view.update(cx, |view, cx| {
4119 view.select_display_ranges(
4120 &[
4121 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4122 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4123 ],
4124 cx,
4125 )
4126 .unwrap();
4127 });
4128
4129 view.update(cx, |view, cx| {
4130 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4131 assert_eq!(
4132 view.selection_ranges(cx),
4133 &[
4134 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4135 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4136 ]
4137 );
4138 });
4139
4140 view.update(cx, |view, cx| {
4141 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4142 assert_eq!(
4143 view.selection_ranges(cx),
4144 &[
4145 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4146 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4147 ]
4148 );
4149 });
4150
4151 view.update(cx, |view, cx| {
4152 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4153 assert_eq!(
4154 view.selection_ranges(cx),
4155 &[
4156 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4157 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4158 ]
4159 );
4160 });
4161
4162 view.update(cx, |view, cx| {
4163 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4164 assert_eq!(
4165 view.selection_ranges(cx),
4166 &[
4167 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4168 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4169 ]
4170 );
4171 });
4172
4173 // Moving to the end of line again is a no-op.
4174 view.update(cx, |view, cx| {
4175 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4176 assert_eq!(
4177 view.selection_ranges(cx),
4178 &[
4179 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4180 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4181 ]
4182 );
4183 });
4184
4185 view.update(cx, |view, cx| {
4186 view.move_left(&MoveLeft, cx);
4187 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4188 assert_eq!(
4189 view.selection_ranges(cx),
4190 &[
4191 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4192 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4193 ]
4194 );
4195 });
4196
4197 view.update(cx, |view, cx| {
4198 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4199 assert_eq!(
4200 view.selection_ranges(cx),
4201 &[
4202 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4203 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4204 ]
4205 );
4206 });
4207
4208 view.update(cx, |view, cx| {
4209 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4210 assert_eq!(
4211 view.selection_ranges(cx),
4212 &[
4213 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4214 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4215 ]
4216 );
4217 });
4218
4219 view.update(cx, |view, cx| {
4220 view.select_to_end_of_line(&SelectToEndOfLine, cx);
4221 assert_eq!(
4222 view.selection_ranges(cx),
4223 &[
4224 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4225 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4226 ]
4227 );
4228 });
4229
4230 view.update(cx, |view, cx| {
4231 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4232 assert_eq!(view.display_text(cx), "ab\n de");
4233 assert_eq!(
4234 view.selection_ranges(cx),
4235 &[
4236 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4237 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4238 ]
4239 );
4240 });
4241
4242 view.update(cx, |view, cx| {
4243 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4244 assert_eq!(view.display_text(cx), "\n");
4245 assert_eq!(
4246 view.selection_ranges(cx),
4247 &[
4248 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4249 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4250 ]
4251 );
4252 });
4253 }
4254
4255 #[gpui::test]
4256 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4257 let buffer =
4258 cx.add_model(|cx| Buffer::new(0, "use std::str::{foo, bar}\n\n {baz.qux()}", cx));
4259 let settings = EditorSettings::test(&cx);
4260 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4261 view.update(cx, |view, cx| {
4262 view.select_display_ranges(
4263 &[
4264 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4265 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4266 ],
4267 cx,
4268 )
4269 .unwrap();
4270 });
4271
4272 view.update(cx, |view, cx| {
4273 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4274 assert_eq!(
4275 view.selection_ranges(cx),
4276 &[
4277 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4278 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4279 ]
4280 );
4281 });
4282
4283 view.update(cx, |view, cx| {
4284 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4285 assert_eq!(
4286 view.selection_ranges(cx),
4287 &[
4288 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4289 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4290 ]
4291 );
4292 });
4293
4294 view.update(cx, |view, cx| {
4295 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4296 assert_eq!(
4297 view.selection_ranges(cx),
4298 &[
4299 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4300 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4301 ]
4302 );
4303 });
4304
4305 view.update(cx, |view, cx| {
4306 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4307 assert_eq!(
4308 view.selection_ranges(cx),
4309 &[
4310 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4311 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4312 ]
4313 );
4314 });
4315
4316 view.update(cx, |view, cx| {
4317 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4318 assert_eq!(
4319 view.selection_ranges(cx),
4320 &[
4321 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4322 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4323 ]
4324 );
4325 });
4326
4327 view.update(cx, |view, cx| {
4328 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4329 assert_eq!(
4330 view.selection_ranges(cx),
4331 &[
4332 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4333 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4334 ]
4335 );
4336 });
4337
4338 view.update(cx, |view, cx| {
4339 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4340 assert_eq!(
4341 view.selection_ranges(cx),
4342 &[
4343 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4344 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4345 ]
4346 );
4347 });
4348
4349 view.update(cx, |view, cx| {
4350 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4351 assert_eq!(
4352 view.selection_ranges(cx),
4353 &[
4354 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4355 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4356 ]
4357 );
4358 });
4359
4360 view.update(cx, |view, cx| {
4361 view.move_right(&MoveRight, cx);
4362 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4363 assert_eq!(
4364 view.selection_ranges(cx),
4365 &[
4366 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4367 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4368 ]
4369 );
4370 });
4371
4372 view.update(cx, |view, cx| {
4373 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4374 assert_eq!(
4375 view.selection_ranges(cx),
4376 &[
4377 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4378 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4379 ]
4380 );
4381 });
4382
4383 view.update(cx, |view, cx| {
4384 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4385 assert_eq!(
4386 view.selection_ranges(cx),
4387 &[
4388 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4389 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4390 ]
4391 );
4392 });
4393 }
4394
4395 #[gpui::test]
4396 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4397 let buffer =
4398 cx.add_model(|cx| Buffer::new(0, "use one::{\n two::three::four::five\n};", cx));
4399 let settings = EditorSettings::test(&cx);
4400 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4401
4402 view.update(cx, |view, cx| {
4403 view.set_wrap_width(140., cx);
4404 assert_eq!(
4405 view.display_text(cx),
4406 "use one::{\n two::three::\n four::five\n};"
4407 );
4408
4409 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4410 .unwrap();
4411
4412 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4413 assert_eq!(
4414 view.selection_ranges(cx),
4415 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4416 );
4417
4418 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4419 assert_eq!(
4420 view.selection_ranges(cx),
4421 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4422 );
4423
4424 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4425 assert_eq!(
4426 view.selection_ranges(cx),
4427 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4428 );
4429
4430 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4431 assert_eq!(
4432 view.selection_ranges(cx),
4433 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4434 );
4435
4436 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4437 assert_eq!(
4438 view.selection_ranges(cx),
4439 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4440 );
4441
4442 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4443 assert_eq!(
4444 view.selection_ranges(cx),
4445 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4446 );
4447 });
4448 }
4449
4450 #[gpui::test]
4451 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4452 let buffer = cx.add_model(|cx| Buffer::new(0, "one two three four", cx));
4453 let settings = EditorSettings::test(&cx);
4454 let (_, view) = cx.add_window(Default::default(), |cx| {
4455 build_editor(buffer.clone(), settings, cx)
4456 });
4457
4458 view.update(cx, |view, cx| {
4459 view.select_display_ranges(
4460 &[
4461 // an empty selection - the preceding word fragment is deleted
4462 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4463 // characters selected - they are deleted
4464 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4465 ],
4466 cx,
4467 )
4468 .unwrap();
4469 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4470 });
4471
4472 assert_eq!(buffer.read(cx).text(), "e two te four");
4473
4474 view.update(cx, |view, cx| {
4475 view.select_display_ranges(
4476 &[
4477 // an empty selection - the following word fragment is deleted
4478 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4479 // characters selected - they are deleted
4480 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4481 ],
4482 cx,
4483 )
4484 .unwrap();
4485 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4486 });
4487
4488 assert_eq!(buffer.read(cx).text(), "e t te our");
4489 }
4490
4491 #[gpui::test]
4492 fn test_newline(cx: &mut gpui::MutableAppContext) {
4493 let buffer = cx.add_model(|cx| Buffer::new(0, "aaaa\n bbbb\n", cx));
4494 let settings = EditorSettings::test(&cx);
4495 let (_, view) = cx.add_window(Default::default(), |cx| {
4496 build_editor(buffer.clone(), settings, cx)
4497 });
4498
4499 view.update(cx, |view, cx| {
4500 view.select_display_ranges(
4501 &[
4502 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4503 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4504 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4505 ],
4506 cx,
4507 )
4508 .unwrap();
4509
4510 view.newline(&Newline, cx);
4511 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
4512 });
4513 }
4514
4515 #[gpui::test]
4516 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4517 let buffer = cx.add_model(|cx| Buffer::new(0, " one two\nthree\n four", cx));
4518 let settings = EditorSettings::test(&cx);
4519 let (_, view) = cx.add_window(Default::default(), |cx| {
4520 build_editor(buffer.clone(), settings, cx)
4521 });
4522
4523 view.update(cx, |view, cx| {
4524 // two selections on the same line
4525 view.select_display_ranges(
4526 &[
4527 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4528 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4529 ],
4530 cx,
4531 )
4532 .unwrap();
4533
4534 // indent from mid-tabstop to full tabstop
4535 view.tab(&Tab, cx);
4536 assert_eq!(view.text(cx), " one two\nthree\n four");
4537 assert_eq!(
4538 view.selection_ranges(cx),
4539 &[
4540 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4541 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4542 ]
4543 );
4544
4545 // outdent from 1 tabstop to 0 tabstops
4546 view.outdent(&Outdent, cx);
4547 assert_eq!(view.text(cx), "one two\nthree\n four");
4548 assert_eq!(
4549 view.selection_ranges(cx),
4550 &[
4551 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4552 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4553 ]
4554 );
4555
4556 // select across line ending
4557 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4558 .unwrap();
4559
4560 // indent and outdent affect only the preceding line
4561 view.tab(&Tab, cx);
4562 assert_eq!(view.text(cx), "one two\n three\n four");
4563 assert_eq!(
4564 view.selection_ranges(cx),
4565 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4566 );
4567 view.outdent(&Outdent, cx);
4568 assert_eq!(view.text(cx), "one two\nthree\n four");
4569 assert_eq!(
4570 view.selection_ranges(cx),
4571 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4572 );
4573 });
4574 }
4575
4576 #[gpui::test]
4577 fn test_backspace(cx: &mut gpui::MutableAppContext) {
4578 let buffer = cx.add_model(|cx| {
4579 Buffer::new(
4580 0,
4581 "one two three\nfour five six\nseven eight nine\nten\n",
4582 cx,
4583 )
4584 });
4585 let settings = EditorSettings::test(&cx);
4586 let (_, view) = cx.add_window(Default::default(), |cx| {
4587 build_editor(buffer.clone(), settings, cx)
4588 });
4589
4590 view.update(cx, |view, cx| {
4591 view.select_display_ranges(
4592 &[
4593 // an empty selection - the preceding character is deleted
4594 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4595 // one character selected - it is deleted
4596 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4597 // a line suffix selected - it is deleted
4598 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4599 ],
4600 cx,
4601 )
4602 .unwrap();
4603 view.backspace(&Backspace, cx);
4604 });
4605
4606 assert_eq!(
4607 buffer.read(cx).text(),
4608 "oe two three\nfou five six\nseven ten\n"
4609 );
4610 }
4611
4612 #[gpui::test]
4613 fn test_delete(cx: &mut gpui::MutableAppContext) {
4614 let buffer = cx.add_model(|cx| {
4615 Buffer::new(
4616 0,
4617 "one two three\nfour five six\nseven eight nine\nten\n",
4618 cx,
4619 )
4620 });
4621 let settings = EditorSettings::test(&cx);
4622 let (_, view) = cx.add_window(Default::default(), |cx| {
4623 build_editor(buffer.clone(), settings, cx)
4624 });
4625
4626 view.update(cx, |view, cx| {
4627 view.select_display_ranges(
4628 &[
4629 // an empty selection - the following character is deleted
4630 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4631 // one character selected - it is deleted
4632 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4633 // a line suffix selected - it is deleted
4634 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4635 ],
4636 cx,
4637 )
4638 .unwrap();
4639 view.delete(&Delete, cx);
4640 });
4641
4642 assert_eq!(
4643 buffer.read(cx).text(),
4644 "on two three\nfou five six\nseven ten\n"
4645 );
4646 }
4647
4648 #[gpui::test]
4649 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4650 let settings = EditorSettings::test(&cx);
4651 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4652 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4653 view.update(cx, |view, cx| {
4654 view.select_display_ranges(
4655 &[
4656 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4657 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4658 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4659 ],
4660 cx,
4661 )
4662 .unwrap();
4663 view.delete_line(&DeleteLine, cx);
4664 assert_eq!(view.display_text(cx), "ghi");
4665 assert_eq!(
4666 view.selection_ranges(cx),
4667 vec![
4668 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4669 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4670 ]
4671 );
4672 });
4673
4674 let settings = EditorSettings::test(&cx);
4675 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4676 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4677 view.update(cx, |view, cx| {
4678 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4679 .unwrap();
4680 view.delete_line(&DeleteLine, cx);
4681 assert_eq!(view.display_text(cx), "ghi\n");
4682 assert_eq!(
4683 view.selection_ranges(cx),
4684 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4685 );
4686 });
4687 }
4688
4689 #[gpui::test]
4690 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4691 let settings = EditorSettings::test(&cx);
4692 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4693 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4694 view.update(cx, |view, cx| {
4695 view.select_display_ranges(
4696 &[
4697 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4698 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4699 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4700 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4701 ],
4702 cx,
4703 )
4704 .unwrap();
4705 view.duplicate_line(&DuplicateLine, cx);
4706 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4707 assert_eq!(
4708 view.selection_ranges(cx),
4709 vec![
4710 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4711 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4712 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4713 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4714 ]
4715 );
4716 });
4717
4718 let settings = EditorSettings::test(&cx);
4719 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4720 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4721 view.update(cx, |view, cx| {
4722 view.select_display_ranges(
4723 &[
4724 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4725 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4726 ],
4727 cx,
4728 )
4729 .unwrap();
4730 view.duplicate_line(&DuplicateLine, cx);
4731 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4732 assert_eq!(
4733 view.selection_ranges(cx),
4734 vec![
4735 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4736 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4737 ]
4738 );
4739 });
4740 }
4741
4742 #[gpui::test]
4743 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4744 let settings = EditorSettings::test(&cx);
4745 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(10, 5), cx));
4746 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4747 view.update(cx, |view, cx| {
4748 view.fold_ranges(
4749 vec![
4750 Point::new(0, 2)..Point::new(1, 2),
4751 Point::new(2, 3)..Point::new(4, 1),
4752 Point::new(7, 0)..Point::new(8, 4),
4753 ],
4754 cx,
4755 );
4756 view.select_display_ranges(
4757 &[
4758 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4759 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4760 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4761 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
4762 ],
4763 cx,
4764 )
4765 .unwrap();
4766 assert_eq!(
4767 view.display_text(cx),
4768 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
4769 );
4770
4771 view.move_line_up(&MoveLineUp, cx);
4772 assert_eq!(
4773 view.display_text(cx),
4774 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
4775 );
4776 assert_eq!(
4777 view.selection_ranges(cx),
4778 vec![
4779 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4780 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4781 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4782 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4783 ]
4784 );
4785 });
4786
4787 view.update(cx, |view, cx| {
4788 view.move_line_down(&MoveLineDown, cx);
4789 assert_eq!(
4790 view.display_text(cx),
4791 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
4792 );
4793 assert_eq!(
4794 view.selection_ranges(cx),
4795 vec![
4796 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4797 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4798 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4799 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4800 ]
4801 );
4802 });
4803
4804 view.update(cx, |view, cx| {
4805 view.move_line_down(&MoveLineDown, cx);
4806 assert_eq!(
4807 view.display_text(cx),
4808 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
4809 );
4810 assert_eq!(
4811 view.selection_ranges(cx),
4812 vec![
4813 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4814 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4815 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4816 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4817 ]
4818 );
4819 });
4820
4821 view.update(cx, |view, cx| {
4822 view.move_line_up(&MoveLineUp, cx);
4823 assert_eq!(
4824 view.display_text(cx),
4825 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
4826 );
4827 assert_eq!(
4828 view.selection_ranges(cx),
4829 vec![
4830 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4831 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4832 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4833 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4834 ]
4835 );
4836 });
4837 }
4838
4839 #[gpui::test]
4840 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
4841 let buffer = cx.add_model(|cx| Buffer::new(0, "one✅ two three four five six ", cx));
4842 let settings = EditorSettings::test(&cx);
4843 let view = cx
4844 .add_window(Default::default(), |cx| {
4845 build_editor(buffer.clone(), settings, cx)
4846 })
4847 .1;
4848
4849 // Cut with three selections. Clipboard text is divided into three slices.
4850 view.update(cx, |view, cx| {
4851 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
4852 view.cut(&Cut, cx);
4853 assert_eq!(view.display_text(cx), "two four six ");
4854 });
4855
4856 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
4857 view.update(cx, |view, cx| {
4858 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
4859 view.paste(&Paste, cx);
4860 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
4861 assert_eq!(
4862 view.selection_ranges(cx),
4863 &[
4864 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4865 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
4866 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
4867 ]
4868 );
4869 });
4870
4871 // Paste again but with only two cursors. Since the number of cursors doesn't
4872 // match the number of slices in the clipboard, the entire clipboard text
4873 // is pasted at each cursor.
4874 view.update(cx, |view, cx| {
4875 view.select_ranges(vec![0..0, 31..31], None, cx);
4876 view.handle_input(&Input("( ".into()), cx);
4877 view.paste(&Paste, cx);
4878 view.handle_input(&Input(") ".into()), cx);
4879 assert_eq!(
4880 view.display_text(cx),
4881 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4882 );
4883 });
4884
4885 view.update(cx, |view, cx| {
4886 view.select_ranges(vec![0..0], None, cx);
4887 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
4888 assert_eq!(
4889 view.display_text(cx),
4890 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4891 );
4892 });
4893
4894 // Cut with three selections, one of which is full-line.
4895 view.update(cx, |view, cx| {
4896 view.select_display_ranges(
4897 &[
4898 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
4899 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4900 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
4901 ],
4902 cx,
4903 )
4904 .unwrap();
4905 view.cut(&Cut, cx);
4906 assert_eq!(
4907 view.display_text(cx),
4908 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4909 );
4910 });
4911
4912 // Paste with three selections, noticing how the copied selection that was full-line
4913 // gets inserted before the second cursor.
4914 view.update(cx, |view, cx| {
4915 view.select_display_ranges(
4916 &[
4917 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4918 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4919 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
4920 ],
4921 cx,
4922 )
4923 .unwrap();
4924 view.paste(&Paste, cx);
4925 assert_eq!(
4926 view.display_text(cx),
4927 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4928 );
4929 assert_eq!(
4930 view.selection_ranges(cx),
4931 &[
4932 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4933 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4934 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
4935 ]
4936 );
4937 });
4938
4939 // Copy with a single cursor only, which writes the whole line into the clipboard.
4940 view.update(cx, |view, cx| {
4941 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
4942 .unwrap();
4943 view.copy(&Copy, cx);
4944 });
4945
4946 // Paste with three selections, noticing how the copied full-line selection is inserted
4947 // before the empty selections but replaces the selection that is non-empty.
4948 view.update(cx, |view, cx| {
4949 view.select_display_ranges(
4950 &[
4951 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4952 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
4953 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4954 ],
4955 cx,
4956 )
4957 .unwrap();
4958 view.paste(&Paste, cx);
4959 assert_eq!(
4960 view.display_text(cx),
4961 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4962 );
4963 assert_eq!(
4964 view.selection_ranges(cx),
4965 &[
4966 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4967 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4968 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
4969 ]
4970 );
4971 });
4972 }
4973
4974 #[gpui::test]
4975 fn test_select_all(cx: &mut gpui::MutableAppContext) {
4976 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\nde\nfgh", cx));
4977 let settings = EditorSettings::test(&cx);
4978 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4979 view.update(cx, |view, cx| {
4980 view.select_all(&SelectAll, cx);
4981 assert_eq!(
4982 view.selection_ranges(cx),
4983 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
4984 );
4985 });
4986 }
4987
4988 #[gpui::test]
4989 fn test_select_line(cx: &mut gpui::MutableAppContext) {
4990 let settings = EditorSettings::test(&cx);
4991 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 5), cx));
4992 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4993 view.update(cx, |view, cx| {
4994 view.select_display_ranges(
4995 &[
4996 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4997 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4998 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4999 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5000 ],
5001 cx,
5002 )
5003 .unwrap();
5004 view.select_line(&SelectLine, cx);
5005 assert_eq!(
5006 view.selection_ranges(cx),
5007 vec![
5008 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5009 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5010 ]
5011 );
5012 });
5013
5014 view.update(cx, |view, cx| {
5015 view.select_line(&SelectLine, cx);
5016 assert_eq!(
5017 view.selection_ranges(cx),
5018 vec![
5019 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5020 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5021 ]
5022 );
5023 });
5024
5025 view.update(cx, |view, cx| {
5026 view.select_line(&SelectLine, cx);
5027 assert_eq!(
5028 view.selection_ranges(cx),
5029 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5030 );
5031 });
5032 }
5033
5034 #[gpui::test]
5035 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5036 let settings = EditorSettings::test(&cx);
5037 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(9, 5), cx));
5038 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5039 view.update(cx, |view, cx| {
5040 view.fold_ranges(
5041 vec![
5042 Point::new(0, 2)..Point::new(1, 2),
5043 Point::new(2, 3)..Point::new(4, 1),
5044 Point::new(7, 0)..Point::new(8, 4),
5045 ],
5046 cx,
5047 );
5048 view.select_display_ranges(
5049 &[
5050 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5051 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5052 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5053 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5054 ],
5055 cx,
5056 )
5057 .unwrap();
5058 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5059 });
5060
5061 view.update(cx, |view, cx| {
5062 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5063 assert_eq!(
5064 view.display_text(cx),
5065 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5066 );
5067 assert_eq!(
5068 view.selection_ranges(cx),
5069 [
5070 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5071 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5072 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5073 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5074 ]
5075 );
5076 });
5077
5078 view.update(cx, |view, cx| {
5079 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5080 .unwrap();
5081 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5082 assert_eq!(
5083 view.display_text(cx),
5084 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5085 );
5086 assert_eq!(
5087 view.selection_ranges(cx),
5088 [
5089 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5090 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5091 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5092 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5093 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5094 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5095 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5096 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5097 ]
5098 );
5099 });
5100 }
5101
5102 #[gpui::test]
5103 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5104 let settings = EditorSettings::test(&cx);
5105 let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefghi\n\njk\nlmno\n", cx));
5106 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5107
5108 view.update(cx, |view, cx| {
5109 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5110 .unwrap();
5111 });
5112 view.update(cx, |view, cx| {
5113 view.add_selection_above(&AddSelectionAbove, cx);
5114 assert_eq!(
5115 view.selection_ranges(cx),
5116 vec![
5117 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5118 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5119 ]
5120 );
5121 });
5122
5123 view.update(cx, |view, cx| {
5124 view.add_selection_above(&AddSelectionAbove, cx);
5125 assert_eq!(
5126 view.selection_ranges(cx),
5127 vec![
5128 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5129 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5130 ]
5131 );
5132 });
5133
5134 view.update(cx, |view, cx| {
5135 view.add_selection_below(&AddSelectionBelow, cx);
5136 assert_eq!(
5137 view.selection_ranges(cx),
5138 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5139 );
5140 });
5141
5142 view.update(cx, |view, cx| {
5143 view.add_selection_below(&AddSelectionBelow, cx);
5144 assert_eq!(
5145 view.selection_ranges(cx),
5146 vec![
5147 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5148 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5149 ]
5150 );
5151 });
5152
5153 view.update(cx, |view, cx| {
5154 view.add_selection_below(&AddSelectionBelow, cx);
5155 assert_eq!(
5156 view.selection_ranges(cx),
5157 vec![
5158 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5159 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5160 ]
5161 );
5162 });
5163
5164 view.update(cx, |view, cx| {
5165 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5166 .unwrap();
5167 });
5168 view.update(cx, |view, cx| {
5169 view.add_selection_below(&AddSelectionBelow, cx);
5170 assert_eq!(
5171 view.selection_ranges(cx),
5172 vec![
5173 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5174 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5175 ]
5176 );
5177 });
5178
5179 view.update(cx, |view, cx| {
5180 view.add_selection_below(&AddSelectionBelow, cx);
5181 assert_eq!(
5182 view.selection_ranges(cx),
5183 vec![
5184 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5185 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5186 ]
5187 );
5188 });
5189
5190 view.update(cx, |view, cx| {
5191 view.add_selection_above(&AddSelectionAbove, cx);
5192 assert_eq!(
5193 view.selection_ranges(cx),
5194 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5195 );
5196 });
5197
5198 view.update(cx, |view, cx| {
5199 view.add_selection_above(&AddSelectionAbove, cx);
5200 assert_eq!(
5201 view.selection_ranges(cx),
5202 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5203 );
5204 });
5205
5206 view.update(cx, |view, cx| {
5207 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5208 .unwrap();
5209 view.add_selection_below(&AddSelectionBelow, cx);
5210 assert_eq!(
5211 view.selection_ranges(cx),
5212 vec![
5213 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5214 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5215 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5216 ]
5217 );
5218 });
5219
5220 view.update(cx, |view, cx| {
5221 view.add_selection_below(&AddSelectionBelow, cx);
5222 assert_eq!(
5223 view.selection_ranges(cx),
5224 vec![
5225 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5226 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5227 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5228 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5229 ]
5230 );
5231 });
5232
5233 view.update(cx, |view, cx| {
5234 view.add_selection_above(&AddSelectionAbove, cx);
5235 assert_eq!(
5236 view.selection_ranges(cx),
5237 vec![
5238 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5239 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5240 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5241 ]
5242 );
5243 });
5244
5245 view.update(cx, |view, cx| {
5246 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5247 .unwrap();
5248 });
5249 view.update(cx, |view, cx| {
5250 view.add_selection_above(&AddSelectionAbove, cx);
5251 assert_eq!(
5252 view.selection_ranges(cx),
5253 vec![
5254 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5255 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5256 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5257 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5258 ]
5259 );
5260 });
5261
5262 view.update(cx, |view, cx| {
5263 view.add_selection_below(&AddSelectionBelow, cx);
5264 assert_eq!(
5265 view.selection_ranges(cx),
5266 vec![
5267 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5268 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5269 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5270 ]
5271 );
5272 });
5273 }
5274
5275 #[gpui::test]
5276 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5277 let settings = cx.read(EditorSettings::test);
5278 let language = Some(Arc::new(Language::new(
5279 LanguageConfig::default(),
5280 tree_sitter_rust::language(),
5281 )));
5282
5283 let text = r#"
5284 use mod1::mod2::{mod3, mod4};
5285
5286 fn fn_1(param1: bool, param2: &str) {
5287 let var1 = "text";
5288 }
5289 "#
5290 .unindent();
5291
5292 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5293 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5294 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
5295 .await;
5296
5297 view.update(&mut cx, |view, cx| {
5298 view.select_display_ranges(
5299 &[
5300 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5301 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5302 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5303 ],
5304 cx,
5305 )
5306 .unwrap();
5307 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5308 });
5309 assert_eq!(
5310 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5311 &[
5312 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5313 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5314 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5315 ]
5316 );
5317
5318 view.update(&mut cx, |view, cx| {
5319 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5320 });
5321 assert_eq!(
5322 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5323 &[
5324 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5325 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5326 ]
5327 );
5328
5329 view.update(&mut cx, |view, cx| {
5330 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5331 });
5332 assert_eq!(
5333 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5334 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5335 );
5336
5337 // Trying to expand the selected syntax node one more time has no effect.
5338 view.update(&mut cx, |view, cx| {
5339 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5340 });
5341 assert_eq!(
5342 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5343 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5344 );
5345
5346 view.update(&mut cx, |view, cx| {
5347 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5348 });
5349 assert_eq!(
5350 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5351 &[
5352 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5353 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5354 ]
5355 );
5356
5357 view.update(&mut cx, |view, cx| {
5358 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5359 });
5360 assert_eq!(
5361 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5362 &[
5363 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5364 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5365 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5366 ]
5367 );
5368
5369 view.update(&mut cx, |view, cx| {
5370 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5371 });
5372 assert_eq!(
5373 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5374 &[
5375 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5376 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5377 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5378 ]
5379 );
5380
5381 // Trying to shrink the selected syntax node one more time has no effect.
5382 view.update(&mut cx, |view, cx| {
5383 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5384 });
5385 assert_eq!(
5386 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5387 &[
5388 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5389 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5390 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5391 ]
5392 );
5393
5394 // Ensure that we keep expanding the selection if the larger selection starts or ends within
5395 // a fold.
5396 view.update(&mut cx, |view, cx| {
5397 view.fold_ranges(
5398 vec![
5399 Point::new(0, 21)..Point::new(0, 24),
5400 Point::new(3, 20)..Point::new(3, 22),
5401 ],
5402 cx,
5403 );
5404 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5405 });
5406 assert_eq!(
5407 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5408 &[
5409 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5410 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5411 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5412 ]
5413 );
5414 }
5415
5416 #[gpui::test]
5417 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5418 let settings = cx.read(EditorSettings::test);
5419 let language = Some(Arc::new(Language::new(
5420 LanguageConfig {
5421 brackets: vec![
5422 BracketPair {
5423 start: "{".to_string(),
5424 end: "}".to_string(),
5425 close: true,
5426 newline: true,
5427 },
5428 BracketPair {
5429 start: "/*".to_string(),
5430 end: " */".to_string(),
5431 close: true,
5432 newline: true,
5433 },
5434 ],
5435 ..Default::default()
5436 },
5437 tree_sitter_rust::language(),
5438 )));
5439
5440 let text = r#"
5441 a
5442
5443 /
5444
5445 "#
5446 .unindent();
5447
5448 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5449 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5450 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
5451 .await;
5452
5453 view.update(&mut cx, |view, cx| {
5454 view.select_display_ranges(
5455 &[
5456 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5457 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5458 ],
5459 cx,
5460 )
5461 .unwrap();
5462 view.handle_input(&Input("{".to_string()), cx);
5463 view.handle_input(&Input("{".to_string()), cx);
5464 view.handle_input(&Input("{".to_string()), cx);
5465 assert_eq!(
5466 view.text(cx),
5467 "
5468 {{{}}}
5469 {{{}}}
5470 /
5471
5472 "
5473 .unindent()
5474 );
5475
5476 view.move_right(&MoveRight, cx);
5477 view.handle_input(&Input("}".to_string()), cx);
5478 view.handle_input(&Input("}".to_string()), cx);
5479 view.handle_input(&Input("}".to_string()), cx);
5480 assert_eq!(
5481 view.text(cx),
5482 "
5483 {{{}}}}
5484 {{{}}}}
5485 /
5486
5487 "
5488 .unindent()
5489 );
5490
5491 view.undo(&Undo, cx);
5492 view.handle_input(&Input("/".to_string()), cx);
5493 view.handle_input(&Input("*".to_string()), cx);
5494 assert_eq!(
5495 view.text(cx),
5496 "
5497 /* */
5498 /* */
5499 /
5500
5501 "
5502 .unindent()
5503 );
5504
5505 view.undo(&Undo, cx);
5506 view.select_display_ranges(
5507 &[
5508 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5509 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5510 ],
5511 cx,
5512 )
5513 .unwrap();
5514 view.handle_input(&Input("*".to_string()), cx);
5515 assert_eq!(
5516 view.text(cx),
5517 "
5518 a
5519
5520 /*
5521 *
5522 "
5523 .unindent()
5524 );
5525 });
5526 }
5527
5528 #[gpui::test]
5529 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5530 let settings = cx.read(EditorSettings::test);
5531 let language = Some(Arc::new(Language::new(
5532 LanguageConfig {
5533 line_comment: Some("// ".to_string()),
5534 ..Default::default()
5535 },
5536 tree_sitter_rust::language(),
5537 )));
5538
5539 let text = "
5540 fn a() {
5541 //b();
5542 // c();
5543 // d();
5544 }
5545 "
5546 .unindent();
5547
5548 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5549 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5550
5551 view.update(&mut cx, |editor, cx| {
5552 // If multiple selections intersect a line, the line is only
5553 // toggled once.
5554 editor
5555 .select_display_ranges(
5556 &[
5557 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5558 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5559 ],
5560 cx,
5561 )
5562 .unwrap();
5563 editor.toggle_comments(&ToggleComments, cx);
5564 assert_eq!(
5565 editor.text(cx),
5566 "
5567 fn a() {
5568 b();
5569 c();
5570 d();
5571 }
5572 "
5573 .unindent()
5574 );
5575
5576 // The comment prefix is inserted at the same column for every line
5577 // in a selection.
5578 editor
5579 .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5580 .unwrap();
5581 editor.toggle_comments(&ToggleComments, cx);
5582 assert_eq!(
5583 editor.text(cx),
5584 "
5585 fn a() {
5586 // b();
5587 // c();
5588 // d();
5589 }
5590 "
5591 .unindent()
5592 );
5593
5594 // If a selection ends at the beginning of a line, that line is not toggled.
5595 editor
5596 .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
5597 .unwrap();
5598 editor.toggle_comments(&ToggleComments, cx);
5599 assert_eq!(
5600 editor.text(cx),
5601 "
5602 fn a() {
5603 // b();
5604 c();
5605 // d();
5606 }
5607 "
5608 .unindent()
5609 );
5610 });
5611 }
5612
5613 #[gpui::test]
5614 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
5615 let settings = cx.read(EditorSettings::test);
5616 let language = Some(Arc::new(Language::new(
5617 LanguageConfig {
5618 brackets: vec![
5619 BracketPair {
5620 start: "{".to_string(),
5621 end: "}".to_string(),
5622 close: true,
5623 newline: true,
5624 },
5625 BracketPair {
5626 start: "/* ".to_string(),
5627 end: " */".to_string(),
5628 close: true,
5629 newline: true,
5630 },
5631 ],
5632 ..Default::default()
5633 },
5634 tree_sitter_rust::language(),
5635 )));
5636
5637 let text = concat!(
5638 "{ }\n", // Suppress rustfmt
5639 " x\n", //
5640 " /* */\n", //
5641 "x\n", //
5642 "{{} }\n", //
5643 );
5644
5645 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5646 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5647 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
5648 .await;
5649
5650 view.update(&mut cx, |view, cx| {
5651 view.select_display_ranges(
5652 &[
5653 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5654 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5655 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5656 ],
5657 cx,
5658 )
5659 .unwrap();
5660 view.newline(&Newline, cx);
5661
5662 assert_eq!(
5663 view.buffer().read(cx).text(),
5664 concat!(
5665 "{ \n", // Suppress rustfmt
5666 "\n", //
5667 "}\n", //
5668 " x\n", //
5669 " /* \n", //
5670 " \n", //
5671 " */\n", //
5672 "x\n", //
5673 "{{} \n", //
5674 "}\n", //
5675 )
5676 );
5677 });
5678 }
5679
5680 impl Editor {
5681 fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
5682 self.intersecting_selections(
5683 self.selection_set_id,
5684 DisplayPoint::zero()..self.max_point(cx),
5685 cx,
5686 )
5687 .into_iter()
5688 .map(|s| {
5689 if s.reversed {
5690 s.end..s.start
5691 } else {
5692 s.start..s.end
5693 }
5694 })
5695 .collect()
5696 }
5697 }
5698
5699 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
5700 let point = DisplayPoint::new(row as u32, column as u32);
5701 point..point
5702 }
5703
5704 fn build_editor(
5705 buffer: ModelHandle<Buffer>,
5706 settings: EditorSettings,
5707 cx: &mut ViewContext<Editor>,
5708 ) -> Editor {
5709 Editor::for_buffer(buffer, move |_| settings.clone(), cx)
5710 }
5711}
5712
5713trait RangeExt<T> {
5714 fn sorted(&self) -> Range<T>;
5715 fn to_inclusive(&self) -> RangeInclusive<T>;
5716}
5717
5718impl<T: Ord + Clone> RangeExt<T> for Range<T> {
5719 fn sorted(&self) -> Self {
5720 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
5721 }
5722
5723 fn to_inclusive(&self) -> RangeInclusive<T> {
5724 self.start.clone()..=self.end.clone()
5725 }
5726}