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