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