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