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