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