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