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