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