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