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 = MultiBuffer::build_simple("123456", cx);
3845 let settings = EditorSettings::test(cx);
3846 let (_, editor) = cx.add_window(Default::default(), |cx| {
3847 build_editor(buffer.clone(), settings, cx)
3848 });
3849
3850 editor.update(cx, |editor, cx| {
3851 editor.start_transaction_at(now, cx);
3852 editor.select_ranges([2..4], None, cx);
3853 editor.insert("cd", cx);
3854 editor.end_transaction_at(now, cx);
3855 assert_eq!(editor.text(cx), "12cd56");
3856 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
3857
3858 editor.start_transaction_at(now, cx);
3859 editor.select_ranges([4..5], None, cx);
3860 editor.insert("e", cx);
3861 editor.end_transaction_at(now, cx);
3862 assert_eq!(editor.text(cx), "12cde6");
3863 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3864
3865 now += buffer.read(cx).transaction_group_interval(cx) + Duration::from_millis(1);
3866 editor.select_ranges([2..2], None, cx);
3867
3868 // Simulate an edit in another editor
3869 buffer.update(cx, |buffer, cx| {
3870 buffer.start_transaction_at(now, cx);
3871 buffer.edit([0..1], "a", cx);
3872 buffer.edit([1..1], "b", cx);
3873 buffer.end_transaction_at(now, cx);
3874 });
3875
3876 assert_eq!(editor.text(cx), "ab2cde6");
3877 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
3878
3879 // Last transaction happened past the group interval in a different editor.
3880 // Undo it individually and don't restore selections.
3881 editor.undo(&Undo, cx);
3882 assert_eq!(editor.text(cx), "12cde6");
3883 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
3884
3885 // First two transactions happened within the group interval in this editor.
3886 // Undo them together and restore selections.
3887 editor.undo(&Undo, cx);
3888 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
3889 assert_eq!(editor.text(cx), "123456");
3890 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
3891
3892 // Redo the first two transactions together.
3893 editor.redo(&Redo, cx);
3894 assert_eq!(editor.text(cx), "12cde6");
3895 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
3896
3897 // Redo the last transaction on its own.
3898 editor.redo(&Redo, cx);
3899 assert_eq!(editor.text(cx), "ab2cde6");
3900 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3901
3902 // Test empty transactions.
3903 editor.start_transaction_at(now, cx);
3904 editor.end_transaction_at(now, cx);
3905 editor.undo(&Undo, cx);
3906 assert_eq!(editor.text(cx), "12cde6");
3907 });
3908 }
3909
3910 #[gpui::test]
3911 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3912 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3913 let settings = EditorSettings::test(cx);
3914 let (_, editor) =
3915 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3916
3917 editor.update(cx, |view, cx| {
3918 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3919 });
3920
3921 assert_eq!(
3922 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3923 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3924 );
3925
3926 editor.update(cx, |view, cx| {
3927 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3928 });
3929
3930 assert_eq!(
3931 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3932 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3933 );
3934
3935 editor.update(cx, |view, cx| {
3936 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3937 });
3938
3939 assert_eq!(
3940 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3941 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3942 );
3943
3944 editor.update(cx, |view, cx| {
3945 view.end_selection(cx);
3946 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3947 });
3948
3949 assert_eq!(
3950 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3951 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3952 );
3953
3954 editor.update(cx, |view, cx| {
3955 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
3956 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
3957 });
3958
3959 eprintln!(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
3960 assert_eq!(
3961 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3962 [
3963 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3964 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3965 ]
3966 );
3967
3968 editor.update(cx, |view, cx| {
3969 view.end_selection(cx);
3970 });
3971
3972 assert_eq!(
3973 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
3974 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3975 );
3976 }
3977
3978 #[gpui::test]
3979 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3980 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3981 let settings = EditorSettings::test(cx);
3982 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3983
3984 view.update(cx, |view, cx| {
3985 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3986 assert_eq!(
3987 view.selected_display_ranges(cx),
3988 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3989 );
3990 });
3991
3992 view.update(cx, |view, cx| {
3993 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3994 assert_eq!(
3995 view.selected_display_ranges(cx),
3996 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3997 );
3998 });
3999
4000 view.update(cx, |view, cx| {
4001 view.cancel(&Cancel, cx);
4002 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4003 assert_eq!(
4004 view.selected_display_ranges(cx),
4005 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4006 );
4007 });
4008 }
4009
4010 #[gpui::test]
4011 fn test_cancel(cx: &mut gpui::MutableAppContext) {
4012 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4013 let settings = EditorSettings::test(cx);
4014 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4015
4016 view.update(cx, |view, cx| {
4017 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
4018 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4019 view.end_selection(cx);
4020
4021 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
4022 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
4023 view.end_selection(cx);
4024 assert_eq!(
4025 view.selected_display_ranges(cx),
4026 [
4027 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4028 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
4029 ]
4030 );
4031 });
4032
4033 view.update(cx, |view, cx| {
4034 view.cancel(&Cancel, cx);
4035 assert_eq!(
4036 view.selected_display_ranges(cx),
4037 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
4038 );
4039 });
4040
4041 view.update(cx, |view, cx| {
4042 view.cancel(&Cancel, cx);
4043 assert_eq!(
4044 view.selected_display_ranges(cx),
4045 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4046 );
4047 });
4048 }
4049
4050 #[gpui::test]
4051 fn test_fold(cx: &mut gpui::MutableAppContext) {
4052 let buffer = MultiBuffer::build_simple(
4053 &"
4054 impl Foo {
4055 // Hello!
4056
4057 fn a() {
4058 1
4059 }
4060
4061 fn b() {
4062 2
4063 }
4064
4065 fn c() {
4066 3
4067 }
4068 }
4069 "
4070 .unindent(),
4071 cx,
4072 );
4073 let settings = EditorSettings::test(&cx);
4074 let (_, view) = cx.add_window(Default::default(), |cx| {
4075 build_editor(buffer.clone(), settings, cx)
4076 });
4077
4078 view.update(cx, |view, cx| {
4079 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
4080 .unwrap();
4081 view.fold(&Fold, cx);
4082 assert_eq!(
4083 view.display_text(cx),
4084 "
4085 impl Foo {
4086 // Hello!
4087
4088 fn a() {
4089 1
4090 }
4091
4092 fn b() {…
4093 }
4094
4095 fn c() {…
4096 }
4097 }
4098 "
4099 .unindent(),
4100 );
4101
4102 view.fold(&Fold, cx);
4103 assert_eq!(
4104 view.display_text(cx),
4105 "
4106 impl Foo {…
4107 }
4108 "
4109 .unindent(),
4110 );
4111
4112 view.unfold(&Unfold, cx);
4113 assert_eq!(
4114 view.display_text(cx),
4115 "
4116 impl Foo {
4117 // Hello!
4118
4119 fn a() {
4120 1
4121 }
4122
4123 fn b() {…
4124 }
4125
4126 fn c() {…
4127 }
4128 }
4129 "
4130 .unindent(),
4131 );
4132
4133 view.unfold(&Unfold, cx);
4134 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4135 });
4136 }
4137
4138 #[gpui::test]
4139 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4140 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4141 let settings = EditorSettings::test(&cx);
4142 let (_, view) = cx.add_window(Default::default(), |cx| {
4143 build_editor(buffer.clone(), settings, cx)
4144 });
4145
4146 buffer.update(cx, |buffer, cx| {
4147 buffer.edit(
4148 vec![
4149 Point::new(1, 0)..Point::new(1, 0),
4150 Point::new(1, 1)..Point::new(1, 1),
4151 ],
4152 "\t",
4153 cx,
4154 );
4155 });
4156
4157 view.update(cx, |view, cx| {
4158 assert_eq!(
4159 view.selected_display_ranges(cx),
4160 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4161 );
4162
4163 view.move_down(&MoveDown, cx);
4164 assert_eq!(
4165 view.selected_display_ranges(cx),
4166 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4167 );
4168
4169 view.move_right(&MoveRight, cx);
4170 assert_eq!(
4171 view.selected_display_ranges(cx),
4172 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4173 );
4174
4175 view.move_left(&MoveLeft, cx);
4176 assert_eq!(
4177 view.selected_display_ranges(cx),
4178 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4179 );
4180
4181 view.move_up(&MoveUp, cx);
4182 assert_eq!(
4183 view.selected_display_ranges(cx),
4184 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4185 );
4186
4187 view.move_to_end(&MoveToEnd, cx);
4188 assert_eq!(
4189 view.selected_display_ranges(cx),
4190 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4191 );
4192
4193 view.move_to_beginning(&MoveToBeginning, cx);
4194 assert_eq!(
4195 view.selected_display_ranges(cx),
4196 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4197 );
4198
4199 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4200 .unwrap();
4201 view.select_to_beginning(&SelectToBeginning, cx);
4202 assert_eq!(
4203 view.selected_display_ranges(cx),
4204 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4205 );
4206
4207 view.select_to_end(&SelectToEnd, cx);
4208 assert_eq!(
4209 view.selected_display_ranges(cx),
4210 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4211 );
4212 });
4213 }
4214
4215 #[gpui::test]
4216 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4217 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4218 let settings = EditorSettings::test(&cx);
4219 let (_, view) = cx.add_window(Default::default(), |cx| {
4220 build_editor(buffer.clone(), settings, cx)
4221 });
4222
4223 assert_eq!('ⓐ'.len_utf8(), 3);
4224 assert_eq!('α'.len_utf8(), 2);
4225
4226 view.update(cx, |view, cx| {
4227 view.fold_ranges(
4228 vec![
4229 Point::new(0, 6)..Point::new(0, 12),
4230 Point::new(1, 2)..Point::new(1, 4),
4231 Point::new(2, 4)..Point::new(2, 8),
4232 ],
4233 cx,
4234 );
4235 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4236
4237 view.move_right(&MoveRight, cx);
4238 assert_eq!(
4239 view.selected_display_ranges(cx),
4240 &[empty_range(0, "ⓐ".len())]
4241 );
4242 view.move_right(&MoveRight, cx);
4243 assert_eq!(
4244 view.selected_display_ranges(cx),
4245 &[empty_range(0, "ⓐⓑ".len())]
4246 );
4247 view.move_right(&MoveRight, cx);
4248 assert_eq!(
4249 view.selected_display_ranges(cx),
4250 &[empty_range(0, "ⓐⓑ…".len())]
4251 );
4252
4253 view.move_down(&MoveDown, cx);
4254 assert_eq!(
4255 view.selected_display_ranges(cx),
4256 &[empty_range(1, "ab…".len())]
4257 );
4258 view.move_left(&MoveLeft, cx);
4259 assert_eq!(
4260 view.selected_display_ranges(cx),
4261 &[empty_range(1, "ab".len())]
4262 );
4263 view.move_left(&MoveLeft, cx);
4264 assert_eq!(
4265 view.selected_display_ranges(cx),
4266 &[empty_range(1, "a".len())]
4267 );
4268
4269 view.move_down(&MoveDown, cx);
4270 assert_eq!(
4271 view.selected_display_ranges(cx),
4272 &[empty_range(2, "α".len())]
4273 );
4274 view.move_right(&MoveRight, cx);
4275 assert_eq!(
4276 view.selected_display_ranges(cx),
4277 &[empty_range(2, "αβ".len())]
4278 );
4279 view.move_right(&MoveRight, cx);
4280 assert_eq!(
4281 view.selected_display_ranges(cx),
4282 &[empty_range(2, "αβ…".len())]
4283 );
4284 view.move_right(&MoveRight, cx);
4285 assert_eq!(
4286 view.selected_display_ranges(cx),
4287 &[empty_range(2, "αβ…ε".len())]
4288 );
4289
4290 view.move_up(&MoveUp, cx);
4291 assert_eq!(
4292 view.selected_display_ranges(cx),
4293 &[empty_range(1, "ab…e".len())]
4294 );
4295 view.move_up(&MoveUp, cx);
4296 assert_eq!(
4297 view.selected_display_ranges(cx),
4298 &[empty_range(0, "ⓐⓑ…ⓔ".len())]
4299 );
4300 view.move_left(&MoveLeft, cx);
4301 assert_eq!(
4302 view.selected_display_ranges(cx),
4303 &[empty_range(0, "ⓐⓑ…".len())]
4304 );
4305 view.move_left(&MoveLeft, cx);
4306 assert_eq!(
4307 view.selected_display_ranges(cx),
4308 &[empty_range(0, "ⓐⓑ".len())]
4309 );
4310 view.move_left(&MoveLeft, cx);
4311 assert_eq!(
4312 view.selected_display_ranges(cx),
4313 &[empty_range(0, "ⓐ".len())]
4314 );
4315 });
4316 }
4317
4318 #[gpui::test]
4319 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4320 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4321 let settings = EditorSettings::test(&cx);
4322 let (_, view) = cx.add_window(Default::default(), |cx| {
4323 build_editor(buffer.clone(), settings, cx)
4324 });
4325 view.update(cx, |view, cx| {
4326 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4327 .unwrap();
4328
4329 view.move_down(&MoveDown, cx);
4330 assert_eq!(
4331 view.selected_display_ranges(cx),
4332 &[empty_range(1, "abcd".len())]
4333 );
4334
4335 view.move_down(&MoveDown, cx);
4336 assert_eq!(
4337 view.selected_display_ranges(cx),
4338 &[empty_range(2, "αβγ".len())]
4339 );
4340
4341 view.move_down(&MoveDown, cx);
4342 assert_eq!(
4343 view.selected_display_ranges(cx),
4344 &[empty_range(3, "abcd".len())]
4345 );
4346
4347 view.move_down(&MoveDown, cx);
4348 assert_eq!(
4349 view.selected_display_ranges(cx),
4350 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4351 );
4352
4353 view.move_up(&MoveUp, cx);
4354 assert_eq!(
4355 view.selected_display_ranges(cx),
4356 &[empty_range(3, "abcd".len())]
4357 );
4358
4359 view.move_up(&MoveUp, cx);
4360 assert_eq!(
4361 view.selected_display_ranges(cx),
4362 &[empty_range(2, "αβγ".len())]
4363 );
4364 });
4365 }
4366
4367 #[gpui::test]
4368 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4369 let buffer = MultiBuffer::build_simple("abc\n def", cx);
4370 let settings = EditorSettings::test(&cx);
4371 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4372 view.update(cx, |view, cx| {
4373 view.select_display_ranges(
4374 &[
4375 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4376 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4377 ],
4378 cx,
4379 )
4380 .unwrap();
4381 });
4382
4383 view.update(cx, |view, cx| {
4384 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4385 assert_eq!(
4386 view.selected_display_ranges(cx),
4387 &[
4388 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4389 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4390 ]
4391 );
4392 });
4393
4394 view.update(cx, |view, cx| {
4395 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4396 assert_eq!(
4397 view.selected_display_ranges(cx),
4398 &[
4399 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4400 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4401 ]
4402 );
4403 });
4404
4405 view.update(cx, |view, cx| {
4406 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4407 assert_eq!(
4408 view.selected_display_ranges(cx),
4409 &[
4410 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4411 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4412 ]
4413 );
4414 });
4415
4416 view.update(cx, |view, cx| {
4417 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4418 assert_eq!(
4419 view.selected_display_ranges(cx),
4420 &[
4421 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4422 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4423 ]
4424 );
4425 });
4426
4427 // Moving to the end of line again is a no-op.
4428 view.update(cx, |view, cx| {
4429 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4430 assert_eq!(
4431 view.selected_display_ranges(cx),
4432 &[
4433 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4434 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4435 ]
4436 );
4437 });
4438
4439 view.update(cx, |view, cx| {
4440 view.move_left(&MoveLeft, cx);
4441 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4442 assert_eq!(
4443 view.selected_display_ranges(cx),
4444 &[
4445 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4446 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4447 ]
4448 );
4449 });
4450
4451 view.update(cx, |view, cx| {
4452 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4453 assert_eq!(
4454 view.selected_display_ranges(cx),
4455 &[
4456 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4457 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4458 ]
4459 );
4460 });
4461
4462 view.update(cx, |view, cx| {
4463 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4464 assert_eq!(
4465 view.selected_display_ranges(cx),
4466 &[
4467 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4468 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4469 ]
4470 );
4471 });
4472
4473 view.update(cx, |view, cx| {
4474 view.select_to_end_of_line(&SelectToEndOfLine, cx);
4475 assert_eq!(
4476 view.selected_display_ranges(cx),
4477 &[
4478 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4479 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4480 ]
4481 );
4482 });
4483
4484 view.update(cx, |view, cx| {
4485 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4486 assert_eq!(view.display_text(cx), "ab\n de");
4487 assert_eq!(
4488 view.selected_display_ranges(cx),
4489 &[
4490 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4491 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4492 ]
4493 );
4494 });
4495
4496 view.update(cx, |view, cx| {
4497 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4498 assert_eq!(view.display_text(cx), "\n");
4499 assert_eq!(
4500 view.selected_display_ranges(cx),
4501 &[
4502 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4503 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4504 ]
4505 );
4506 });
4507 }
4508
4509 #[gpui::test]
4510 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4511 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
4512 let settings = EditorSettings::test(&cx);
4513 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4514 view.update(cx, |view, cx| {
4515 view.select_display_ranges(
4516 &[
4517 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4518 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4519 ],
4520 cx,
4521 )
4522 .unwrap();
4523 });
4524
4525 view.update(cx, |view, cx| {
4526 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4527 assert_eq!(
4528 view.selected_display_ranges(cx),
4529 &[
4530 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4531 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4532 ]
4533 );
4534 });
4535
4536 view.update(cx, |view, cx| {
4537 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4538 assert_eq!(
4539 view.selected_display_ranges(cx),
4540 &[
4541 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4542 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4543 ]
4544 );
4545 });
4546
4547 view.update(cx, |view, cx| {
4548 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4549 assert_eq!(
4550 view.selected_display_ranges(cx),
4551 &[
4552 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4553 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4554 ]
4555 );
4556 });
4557
4558 view.update(cx, |view, cx| {
4559 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4560 assert_eq!(
4561 view.selected_display_ranges(cx),
4562 &[
4563 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4564 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4565 ]
4566 );
4567 });
4568
4569 view.update(cx, |view, cx| {
4570 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4571 assert_eq!(
4572 view.selected_display_ranges(cx),
4573 &[
4574 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4575 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4576 ]
4577 );
4578 });
4579
4580 view.update(cx, |view, cx| {
4581 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4582 assert_eq!(
4583 view.selected_display_ranges(cx),
4584 &[
4585 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4586 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4587 ]
4588 );
4589 });
4590
4591 view.update(cx, |view, cx| {
4592 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4593 assert_eq!(
4594 view.selected_display_ranges(cx),
4595 &[
4596 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4597 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4598 ]
4599 );
4600 });
4601
4602 view.update(cx, |view, cx| {
4603 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4604 assert_eq!(
4605 view.selected_display_ranges(cx),
4606 &[
4607 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4608 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4609 ]
4610 );
4611 });
4612
4613 view.update(cx, |view, cx| {
4614 view.move_right(&MoveRight, cx);
4615 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4616 assert_eq!(
4617 view.selected_display_ranges(cx),
4618 &[
4619 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4620 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4621 ]
4622 );
4623 });
4624
4625 view.update(cx, |view, cx| {
4626 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4627 assert_eq!(
4628 view.selected_display_ranges(cx),
4629 &[
4630 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4631 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4632 ]
4633 );
4634 });
4635
4636 view.update(cx, |view, cx| {
4637 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4638 assert_eq!(
4639 view.selected_display_ranges(cx),
4640 &[
4641 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4642 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4643 ]
4644 );
4645 });
4646 }
4647
4648 #[gpui::test]
4649 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4650 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
4651 let settings = EditorSettings::test(&cx);
4652 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4653
4654 view.update(cx, |view, cx| {
4655 view.set_wrap_width(Some(140.), cx);
4656 assert_eq!(
4657 view.display_text(cx),
4658 "use one::{\n two::three::\n four::five\n};"
4659 );
4660
4661 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4662 .unwrap();
4663
4664 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4665 assert_eq!(
4666 view.selected_display_ranges(cx),
4667 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4668 );
4669
4670 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4671 assert_eq!(
4672 view.selected_display_ranges(cx),
4673 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4674 );
4675
4676 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4677 assert_eq!(
4678 view.selected_display_ranges(cx),
4679 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4680 );
4681
4682 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4683 assert_eq!(
4684 view.selected_display_ranges(cx),
4685 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4686 );
4687
4688 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4689 assert_eq!(
4690 view.selected_display_ranges(cx),
4691 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4692 );
4693
4694 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4695 assert_eq!(
4696 view.selected_display_ranges(cx),
4697 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4698 );
4699 });
4700 }
4701
4702 #[gpui::test]
4703 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4704 let buffer = MultiBuffer::build_simple("one two three four", cx);
4705 let settings = EditorSettings::test(&cx);
4706 let (_, view) = cx.add_window(Default::default(), |cx| {
4707 build_editor(buffer.clone(), settings, cx)
4708 });
4709
4710 view.update(cx, |view, cx| {
4711 view.select_display_ranges(
4712 &[
4713 // an empty selection - the preceding word fragment is deleted
4714 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4715 // characters selected - they are deleted
4716 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4717 ],
4718 cx,
4719 )
4720 .unwrap();
4721 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4722 });
4723
4724 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
4725
4726 view.update(cx, |view, cx| {
4727 view.select_display_ranges(
4728 &[
4729 // an empty selection - the following word fragment is deleted
4730 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4731 // characters selected - they are deleted
4732 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4733 ],
4734 cx,
4735 )
4736 .unwrap();
4737 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4738 });
4739
4740 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
4741 }
4742
4743 #[gpui::test]
4744 fn test_newline(cx: &mut gpui::MutableAppContext) {
4745 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
4746 let settings = EditorSettings::test(&cx);
4747 let (_, view) = cx.add_window(Default::default(), |cx| {
4748 build_editor(buffer.clone(), settings, cx)
4749 });
4750
4751 view.update(cx, |view, cx| {
4752 view.select_display_ranges(
4753 &[
4754 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4755 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4756 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4757 ],
4758 cx,
4759 )
4760 .unwrap();
4761
4762 view.newline(&Newline, cx);
4763 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
4764 });
4765 }
4766
4767 #[gpui::test]
4768 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4769 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
4770 let settings = EditorSettings::test(&cx);
4771 let (_, view) = cx.add_window(Default::default(), |cx| {
4772 build_editor(buffer.clone(), settings, cx)
4773 });
4774
4775 view.update(cx, |view, cx| {
4776 // two selections on the same line
4777 view.select_display_ranges(
4778 &[
4779 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4780 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4781 ],
4782 cx,
4783 )
4784 .unwrap();
4785
4786 // indent from mid-tabstop to full tabstop
4787 view.tab(&Tab, cx);
4788 assert_eq!(view.text(cx), " one two\nthree\n four");
4789 assert_eq!(
4790 view.selected_display_ranges(cx),
4791 &[
4792 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4793 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4794 ]
4795 );
4796
4797 // outdent from 1 tabstop to 0 tabstops
4798 view.outdent(&Outdent, cx);
4799 assert_eq!(view.text(cx), "one two\nthree\n four");
4800 assert_eq!(
4801 view.selected_display_ranges(cx),
4802 &[
4803 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4804 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4805 ]
4806 );
4807
4808 // select across line ending
4809 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4810 .unwrap();
4811
4812 // indent and outdent affect only the preceding line
4813 view.tab(&Tab, cx);
4814 assert_eq!(view.text(cx), "one two\n three\n four");
4815 assert_eq!(
4816 view.selected_display_ranges(cx),
4817 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4818 );
4819 view.outdent(&Outdent, cx);
4820 assert_eq!(view.text(cx), "one two\nthree\n four");
4821 assert_eq!(
4822 view.selected_display_ranges(cx),
4823 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4824 );
4825 });
4826 }
4827
4828 #[gpui::test]
4829 fn test_backspace(cx: &mut gpui::MutableAppContext) {
4830 let buffer =
4831 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4832 let settings = EditorSettings::test(&cx);
4833 let (_, view) = cx.add_window(Default::default(), |cx| {
4834 build_editor(buffer.clone(), settings, cx)
4835 });
4836
4837 view.update(cx, |view, cx| {
4838 view.select_display_ranges(
4839 &[
4840 // an empty selection - the preceding character is deleted
4841 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4842 // one character selected - it is deleted
4843 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4844 // a line suffix selected - it is deleted
4845 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4846 ],
4847 cx,
4848 )
4849 .unwrap();
4850 view.backspace(&Backspace, cx);
4851 });
4852
4853 assert_eq!(
4854 buffer.read(cx).read(cx).text(),
4855 "oe two three\nfou five six\nseven ten\n"
4856 );
4857 }
4858
4859 #[gpui::test]
4860 fn test_delete(cx: &mut gpui::MutableAppContext) {
4861 let buffer =
4862 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4863 let settings = EditorSettings::test(&cx);
4864 let (_, view) = cx.add_window(Default::default(), |cx| {
4865 build_editor(buffer.clone(), settings, cx)
4866 });
4867
4868 view.update(cx, |view, cx| {
4869 view.select_display_ranges(
4870 &[
4871 // an empty selection - the following character is deleted
4872 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4873 // one character selected - it is deleted
4874 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4875 // a line suffix selected - it is deleted
4876 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4877 ],
4878 cx,
4879 )
4880 .unwrap();
4881 view.delete(&Delete, cx);
4882 });
4883
4884 assert_eq!(
4885 buffer.read(cx).read(cx).text(),
4886 "on two three\nfou five six\nseven ten\n"
4887 );
4888 }
4889
4890 #[gpui::test]
4891 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4892 let settings = EditorSettings::test(&cx);
4893 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4894 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4895 view.update(cx, |view, cx| {
4896 view.select_display_ranges(
4897 &[
4898 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4899 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4900 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4901 ],
4902 cx,
4903 )
4904 .unwrap();
4905 view.delete_line(&DeleteLine, cx);
4906 assert_eq!(view.display_text(cx), "ghi");
4907 assert_eq!(
4908 view.selected_display_ranges(cx),
4909 vec![
4910 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4911 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4912 ]
4913 );
4914 });
4915
4916 let settings = EditorSettings::test(&cx);
4917 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4918 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4919 view.update(cx, |view, cx| {
4920 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4921 .unwrap();
4922 view.delete_line(&DeleteLine, cx);
4923 assert_eq!(view.display_text(cx), "ghi\n");
4924 assert_eq!(
4925 view.selected_display_ranges(cx),
4926 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4927 );
4928 });
4929 }
4930
4931 #[gpui::test]
4932 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4933 let settings = EditorSettings::test(&cx);
4934 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4935 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4936 view.update(cx, |view, cx| {
4937 view.select_display_ranges(
4938 &[
4939 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4940 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4941 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4942 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4943 ],
4944 cx,
4945 )
4946 .unwrap();
4947 view.duplicate_line(&DuplicateLine, cx);
4948 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4949 assert_eq!(
4950 view.selected_display_ranges(cx),
4951 vec![
4952 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4953 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4954 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4955 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4956 ]
4957 );
4958 });
4959
4960 let settings = EditorSettings::test(&cx);
4961 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4962 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4963 view.update(cx, |view, cx| {
4964 view.select_display_ranges(
4965 &[
4966 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4967 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4968 ],
4969 cx,
4970 )
4971 .unwrap();
4972 view.duplicate_line(&DuplicateLine, cx);
4973 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4974 assert_eq!(
4975 view.selected_display_ranges(cx),
4976 vec![
4977 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4978 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4979 ]
4980 );
4981 });
4982 }
4983
4984 #[gpui::test]
4985 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4986 let settings = EditorSettings::test(&cx);
4987 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
4988 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4989 view.update(cx, |view, cx| {
4990 view.fold_ranges(
4991 vec![
4992 Point::new(0, 2)..Point::new(1, 2),
4993 Point::new(2, 3)..Point::new(4, 1),
4994 Point::new(7, 0)..Point::new(8, 4),
4995 ],
4996 cx,
4997 );
4998 view.select_display_ranges(
4999 &[
5000 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5001 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5002 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5003 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
5004 ],
5005 cx,
5006 )
5007 .unwrap();
5008 assert_eq!(
5009 view.display_text(cx),
5010 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
5011 );
5012
5013 view.move_line_up(&MoveLineUp, cx);
5014 assert_eq!(
5015 view.display_text(cx),
5016 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
5017 );
5018 assert_eq!(
5019 view.selected_display_ranges(cx),
5020 vec![
5021 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5022 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5023 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5024 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5025 ]
5026 );
5027 });
5028
5029 view.update(cx, |view, cx| {
5030 view.move_line_down(&MoveLineDown, cx);
5031 assert_eq!(
5032 view.display_text(cx),
5033 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
5034 );
5035 assert_eq!(
5036 view.selected_display_ranges(cx),
5037 vec![
5038 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5039 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5040 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5041 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5042 ]
5043 );
5044 });
5045
5046 view.update(cx, |view, cx| {
5047 view.move_line_down(&MoveLineDown, cx);
5048 assert_eq!(
5049 view.display_text(cx),
5050 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5051 );
5052 assert_eq!(
5053 view.selected_display_ranges(cx),
5054 vec![
5055 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5056 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5057 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5058 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5059 ]
5060 );
5061 });
5062
5063 view.update(cx, |view, cx| {
5064 view.move_line_up(&MoveLineUp, cx);
5065 assert_eq!(
5066 view.display_text(cx),
5067 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5068 );
5069 assert_eq!(
5070 view.selected_display_ranges(cx),
5071 vec![
5072 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5073 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5074 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5075 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5076 ]
5077 );
5078 });
5079 }
5080
5081 #[gpui::test]
5082 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5083 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5084 let settings = EditorSettings::test(&cx);
5085 let view = cx
5086 .add_window(Default::default(), |cx| {
5087 build_editor(buffer.clone(), settings, cx)
5088 })
5089 .1;
5090
5091 // Cut with three selections. Clipboard text is divided into three slices.
5092 view.update(cx, |view, cx| {
5093 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5094 view.cut(&Cut, cx);
5095 assert_eq!(view.display_text(cx), "two four six ");
5096 });
5097
5098 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5099 view.update(cx, |view, cx| {
5100 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5101 view.paste(&Paste, cx);
5102 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5103 assert_eq!(
5104 view.selected_display_ranges(cx),
5105 &[
5106 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5107 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5108 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5109 ]
5110 );
5111 });
5112
5113 // Paste again but with only two cursors. Since the number of cursors doesn't
5114 // match the number of slices in the clipboard, the entire clipboard text
5115 // is pasted at each cursor.
5116 view.update(cx, |view, cx| {
5117 view.select_ranges(vec![0..0, 31..31], None, cx);
5118 view.handle_input(&Input("( ".into()), cx);
5119 view.paste(&Paste, cx);
5120 view.handle_input(&Input(") ".into()), cx);
5121 assert_eq!(
5122 view.display_text(cx),
5123 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5124 );
5125 });
5126
5127 view.update(cx, |view, cx| {
5128 view.select_ranges(vec![0..0], None, cx);
5129 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5130 assert_eq!(
5131 view.display_text(cx),
5132 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5133 );
5134 });
5135
5136 // Cut with three selections, one of which is full-line.
5137 view.update(cx, |view, cx| {
5138 view.select_display_ranges(
5139 &[
5140 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5141 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5142 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5143 ],
5144 cx,
5145 )
5146 .unwrap();
5147 view.cut(&Cut, cx);
5148 assert_eq!(
5149 view.display_text(cx),
5150 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5151 );
5152 });
5153
5154 // Paste with three selections, noticing how the copied selection that was full-line
5155 // gets inserted before the second cursor.
5156 view.update(cx, |view, cx| {
5157 view.select_display_ranges(
5158 &[
5159 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5160 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5161 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5162 ],
5163 cx,
5164 )
5165 .unwrap();
5166 view.paste(&Paste, cx);
5167 assert_eq!(
5168 view.display_text(cx),
5169 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5170 );
5171 assert_eq!(
5172 view.selected_display_ranges(cx),
5173 &[
5174 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5175 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5176 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5177 ]
5178 );
5179 });
5180
5181 // Copy with a single cursor only, which writes the whole line into the clipboard.
5182 view.update(cx, |view, cx| {
5183 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
5184 .unwrap();
5185 view.copy(&Copy, cx);
5186 });
5187
5188 // Paste with three selections, noticing how the copied full-line selection is inserted
5189 // before the empty selections but replaces the selection that is non-empty.
5190 view.update(cx, |view, cx| {
5191 view.select_display_ranges(
5192 &[
5193 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5194 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5195 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5196 ],
5197 cx,
5198 )
5199 .unwrap();
5200 view.paste(&Paste, cx);
5201 assert_eq!(
5202 view.display_text(cx),
5203 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5204 );
5205 assert_eq!(
5206 view.selected_display_ranges(cx),
5207 &[
5208 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5209 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5210 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5211 ]
5212 );
5213 });
5214 }
5215
5216 #[gpui::test]
5217 fn test_select_all(cx: &mut gpui::MutableAppContext) {
5218 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5219 let settings = EditorSettings::test(&cx);
5220 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5221 view.update(cx, |view, cx| {
5222 view.select_all(&SelectAll, cx);
5223 assert_eq!(
5224 view.selected_display_ranges(cx),
5225 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5226 );
5227 });
5228 }
5229
5230 #[gpui::test]
5231 fn test_select_line(cx: &mut gpui::MutableAppContext) {
5232 let settings = EditorSettings::test(&cx);
5233 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5234 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5235 view.update(cx, |view, cx| {
5236 view.select_display_ranges(
5237 &[
5238 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5239 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5240 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5241 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5242 ],
5243 cx,
5244 )
5245 .unwrap();
5246 view.select_line(&SelectLine, cx);
5247 assert_eq!(
5248 view.selected_display_ranges(cx),
5249 vec![
5250 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5251 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5252 ]
5253 );
5254 });
5255
5256 view.update(cx, |view, cx| {
5257 view.select_line(&SelectLine, cx);
5258 assert_eq!(
5259 view.selected_display_ranges(cx),
5260 vec![
5261 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5262 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5263 ]
5264 );
5265 });
5266
5267 view.update(cx, |view, cx| {
5268 view.select_line(&SelectLine, cx);
5269 assert_eq!(
5270 view.selected_display_ranges(cx),
5271 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5272 );
5273 });
5274 }
5275
5276 #[gpui::test]
5277 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5278 let settings = EditorSettings::test(&cx);
5279 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5280 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5281 view.update(cx, |view, cx| {
5282 view.fold_ranges(
5283 vec![
5284 Point::new(0, 2)..Point::new(1, 2),
5285 Point::new(2, 3)..Point::new(4, 1),
5286 Point::new(7, 0)..Point::new(8, 4),
5287 ],
5288 cx,
5289 );
5290 view.select_display_ranges(
5291 &[
5292 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5293 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5294 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5295 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5296 ],
5297 cx,
5298 )
5299 .unwrap();
5300 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5301 });
5302
5303 view.update(cx, |view, cx| {
5304 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5305 assert_eq!(
5306 view.display_text(cx),
5307 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5308 );
5309 assert_eq!(
5310 view.selected_display_ranges(cx),
5311 [
5312 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5313 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5314 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5315 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5316 ]
5317 );
5318 });
5319
5320 view.update(cx, |view, cx| {
5321 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5322 .unwrap();
5323 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5324 assert_eq!(
5325 view.display_text(cx),
5326 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5327 );
5328 assert_eq!(
5329 view.selected_display_ranges(cx),
5330 [
5331 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5332 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5333 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5334 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5335 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5336 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5337 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5338 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5339 ]
5340 );
5341 });
5342 }
5343
5344 #[gpui::test]
5345 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5346 let settings = EditorSettings::test(&cx);
5347 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5348 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5349
5350 view.update(cx, |view, cx| {
5351 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5352 .unwrap();
5353 });
5354 view.update(cx, |view, cx| {
5355 view.add_selection_above(&AddSelectionAbove, cx);
5356 assert_eq!(
5357 view.selected_display_ranges(cx),
5358 vec![
5359 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5360 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5361 ]
5362 );
5363 });
5364
5365 view.update(cx, |view, cx| {
5366 view.add_selection_above(&AddSelectionAbove, cx);
5367 assert_eq!(
5368 view.selected_display_ranges(cx),
5369 vec![
5370 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5371 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5372 ]
5373 );
5374 });
5375
5376 view.update(cx, |view, cx| {
5377 view.add_selection_below(&AddSelectionBelow, cx);
5378 assert_eq!(
5379 view.selected_display_ranges(cx),
5380 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5381 );
5382 });
5383
5384 view.update(cx, |view, cx| {
5385 view.add_selection_below(&AddSelectionBelow, cx);
5386 assert_eq!(
5387 view.selected_display_ranges(cx),
5388 vec![
5389 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5390 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5391 ]
5392 );
5393 });
5394
5395 view.update(cx, |view, cx| {
5396 view.add_selection_below(&AddSelectionBelow, cx);
5397 assert_eq!(
5398 view.selected_display_ranges(cx),
5399 vec![
5400 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5401 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5402 ]
5403 );
5404 });
5405
5406 view.update(cx, |view, cx| {
5407 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5408 .unwrap();
5409 });
5410 view.update(cx, |view, cx| {
5411 view.add_selection_below(&AddSelectionBelow, cx);
5412 assert_eq!(
5413 view.selected_display_ranges(cx),
5414 vec![
5415 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5416 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5417 ]
5418 );
5419 });
5420
5421 view.update(cx, |view, cx| {
5422 view.add_selection_below(&AddSelectionBelow, cx);
5423 assert_eq!(
5424 view.selected_display_ranges(cx),
5425 vec![
5426 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5427 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5428 ]
5429 );
5430 });
5431
5432 view.update(cx, |view, cx| {
5433 view.add_selection_above(&AddSelectionAbove, cx);
5434 assert_eq!(
5435 view.selected_display_ranges(cx),
5436 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5437 );
5438 });
5439
5440 view.update(cx, |view, cx| {
5441 view.add_selection_above(&AddSelectionAbove, cx);
5442 assert_eq!(
5443 view.selected_display_ranges(cx),
5444 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5445 );
5446 });
5447
5448 view.update(cx, |view, cx| {
5449 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5450 .unwrap();
5451 view.add_selection_below(&AddSelectionBelow, cx);
5452 assert_eq!(
5453 view.selected_display_ranges(cx),
5454 vec![
5455 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5456 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5457 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5458 ]
5459 );
5460 });
5461
5462 view.update(cx, |view, cx| {
5463 view.add_selection_below(&AddSelectionBelow, cx);
5464 assert_eq!(
5465 view.selected_display_ranges(cx),
5466 vec![
5467 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5468 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5469 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5470 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5471 ]
5472 );
5473 });
5474
5475 view.update(cx, |view, cx| {
5476 view.add_selection_above(&AddSelectionAbove, cx);
5477 assert_eq!(
5478 view.selected_display_ranges(cx),
5479 vec![
5480 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5481 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5482 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5483 ]
5484 );
5485 });
5486
5487 view.update(cx, |view, cx| {
5488 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5489 .unwrap();
5490 });
5491 view.update(cx, |view, cx| {
5492 view.add_selection_above(&AddSelectionAbove, cx);
5493 assert_eq!(
5494 view.selected_display_ranges(cx),
5495 vec![
5496 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5497 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5498 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5499 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5500 ]
5501 );
5502 });
5503
5504 view.update(cx, |view, cx| {
5505 view.add_selection_below(&AddSelectionBelow, cx);
5506 assert_eq!(
5507 view.selected_display_ranges(cx),
5508 vec![
5509 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5510 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5511 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5512 ]
5513 );
5514 });
5515 }
5516
5517 #[gpui::test]
5518 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5519 let settings = cx.read(EditorSettings::test);
5520 let language = Some(Arc::new(Language::new(
5521 LanguageConfig::default(),
5522 Some(tree_sitter_rust::language()),
5523 )));
5524
5525 let text = r#"
5526 use mod1::mod2::{mod3, mod4};
5527
5528 fn fn_1(param1: bool, param2: &str) {
5529 let var1 = "text";
5530 }
5531 "#
5532 .unindent();
5533
5534 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5535 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5536 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5537 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5538 .await;
5539
5540 view.update(&mut cx, |view, cx| {
5541 view.select_display_ranges(
5542 &[
5543 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5544 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5545 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5546 ],
5547 cx,
5548 )
5549 .unwrap();
5550 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5551 });
5552 assert_eq!(
5553 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5554 &[
5555 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5556 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5557 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5558 ]
5559 );
5560
5561 view.update(&mut cx, |view, cx| {
5562 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5563 });
5564 assert_eq!(
5565 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5566 &[
5567 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5568 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5569 ]
5570 );
5571
5572 view.update(&mut cx, |view, cx| {
5573 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5574 });
5575 assert_eq!(
5576 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5577 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5578 );
5579
5580 // Trying to expand the selected syntax node one more time has no effect.
5581 view.update(&mut cx, |view, cx| {
5582 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5583 });
5584 assert_eq!(
5585 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5586 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5587 );
5588
5589 view.update(&mut cx, |view, cx| {
5590 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5591 });
5592 assert_eq!(
5593 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5594 &[
5595 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5596 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5597 ]
5598 );
5599
5600 view.update(&mut cx, |view, cx| {
5601 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5602 });
5603 assert_eq!(
5604 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5605 &[
5606 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5607 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5608 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5609 ]
5610 );
5611
5612 view.update(&mut cx, |view, cx| {
5613 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5614 });
5615 assert_eq!(
5616 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5617 &[
5618 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5619 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5620 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5621 ]
5622 );
5623
5624 // Trying to shrink the selected syntax node one more time has no effect.
5625 view.update(&mut cx, |view, cx| {
5626 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5627 });
5628 assert_eq!(
5629 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5630 &[
5631 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5632 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5633 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5634 ]
5635 );
5636
5637 // Ensure that we keep expanding the selection if the larger selection starts or ends within
5638 // a fold.
5639 view.update(&mut cx, |view, cx| {
5640 view.fold_ranges(
5641 vec![
5642 Point::new(0, 21)..Point::new(0, 24),
5643 Point::new(3, 20)..Point::new(3, 22),
5644 ],
5645 cx,
5646 );
5647 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5648 });
5649 assert_eq!(
5650 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5651 &[
5652 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5653 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5654 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5655 ]
5656 );
5657 }
5658
5659 #[gpui::test]
5660 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5661 let settings = cx.read(EditorSettings::test);
5662 let language = Some(Arc::new(Language::new(
5663 LanguageConfig {
5664 brackets: vec![
5665 BracketPair {
5666 start: "{".to_string(),
5667 end: "}".to_string(),
5668 close: true,
5669 newline: true,
5670 },
5671 BracketPair {
5672 start: "/*".to_string(),
5673 end: " */".to_string(),
5674 close: true,
5675 newline: true,
5676 },
5677 ],
5678 ..Default::default()
5679 },
5680 Some(tree_sitter_rust::language()),
5681 )));
5682
5683 let text = r#"
5684 a
5685
5686 /
5687
5688 "#
5689 .unindent();
5690
5691 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5692 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5693 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5694 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5695 .await;
5696
5697 view.update(&mut cx, |view, cx| {
5698 view.select_display_ranges(
5699 &[
5700 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5701 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5702 ],
5703 cx,
5704 )
5705 .unwrap();
5706 view.handle_input(&Input("{".to_string()), cx);
5707 view.handle_input(&Input("{".to_string()), cx);
5708 view.handle_input(&Input("{".to_string()), cx);
5709 assert_eq!(
5710 view.text(cx),
5711 "
5712 {{{}}}
5713 {{{}}}
5714 /
5715
5716 "
5717 .unindent()
5718 );
5719
5720 view.move_right(&MoveRight, cx);
5721 view.handle_input(&Input("}".to_string()), cx);
5722 view.handle_input(&Input("}".to_string()), cx);
5723 view.handle_input(&Input("}".to_string()), cx);
5724 assert_eq!(
5725 view.text(cx),
5726 "
5727 {{{}}}}
5728 {{{}}}}
5729 /
5730
5731 "
5732 .unindent()
5733 );
5734
5735 view.undo(&Undo, cx);
5736 view.handle_input(&Input("/".to_string()), cx);
5737 view.handle_input(&Input("*".to_string()), cx);
5738 assert_eq!(
5739 view.text(cx),
5740 "
5741 /* */
5742 /* */
5743 /
5744
5745 "
5746 .unindent()
5747 );
5748
5749 view.undo(&Undo, cx);
5750 view.select_display_ranges(
5751 &[
5752 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5753 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5754 ],
5755 cx,
5756 )
5757 .unwrap();
5758 view.handle_input(&Input("*".to_string()), cx);
5759 assert_eq!(
5760 view.text(cx),
5761 "
5762 a
5763
5764 /*
5765 *
5766 "
5767 .unindent()
5768 );
5769 });
5770 }
5771
5772 #[gpui::test]
5773 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5774 let settings = cx.read(EditorSettings::test);
5775 let language = Some(Arc::new(Language::new(
5776 LanguageConfig {
5777 line_comment: Some("// ".to_string()),
5778 ..Default::default()
5779 },
5780 Some(tree_sitter_rust::language()),
5781 )));
5782
5783 let text = "
5784 fn a() {
5785 //b();
5786 // c();
5787 // d();
5788 }
5789 "
5790 .unindent();
5791
5792 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5793 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5794 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5795
5796 view.update(&mut cx, |editor, cx| {
5797 // If multiple selections intersect a line, the line is only
5798 // toggled once.
5799 editor
5800 .select_display_ranges(
5801 &[
5802 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5803 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5804 ],
5805 cx,
5806 )
5807 .unwrap();
5808 editor.toggle_comments(&ToggleComments, cx);
5809 assert_eq!(
5810 editor.text(cx),
5811 "
5812 fn a() {
5813 b();
5814 c();
5815 d();
5816 }
5817 "
5818 .unindent()
5819 );
5820
5821 // The comment prefix is inserted at the same column for every line
5822 // in a selection.
5823 editor
5824 .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5825 .unwrap();
5826 editor.toggle_comments(&ToggleComments, cx);
5827 assert_eq!(
5828 editor.text(cx),
5829 "
5830 fn a() {
5831 // b();
5832 // c();
5833 // d();
5834 }
5835 "
5836 .unindent()
5837 );
5838
5839 // If a selection ends at the beginning of a line, that line is not toggled.
5840 editor
5841 .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
5842 .unwrap();
5843 editor.toggle_comments(&ToggleComments, cx);
5844 assert_eq!(
5845 editor.text(cx),
5846 "
5847 fn a() {
5848 // b();
5849 c();
5850 // d();
5851 }
5852 "
5853 .unindent()
5854 );
5855 });
5856 }
5857
5858 #[gpui::test]
5859 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
5860 let settings = cx.read(EditorSettings::test);
5861 let language = Some(Arc::new(Language::new(
5862 LanguageConfig {
5863 brackets: vec![
5864 BracketPair {
5865 start: "{".to_string(),
5866 end: "}".to_string(),
5867 close: true,
5868 newline: true,
5869 },
5870 BracketPair {
5871 start: "/* ".to_string(),
5872 end: " */".to_string(),
5873 close: true,
5874 newline: true,
5875 },
5876 ],
5877 ..Default::default()
5878 },
5879 Some(tree_sitter_rust::language()),
5880 )));
5881
5882 let text = concat!(
5883 "{ }\n", // Suppress rustfmt
5884 " x\n", //
5885 " /* */\n", //
5886 "x\n", //
5887 "{{} }\n", //
5888 );
5889
5890 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5891 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5892 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5893 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5894 .await;
5895
5896 view.update(&mut cx, |view, cx| {
5897 view.select_display_ranges(
5898 &[
5899 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5900 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5901 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5902 ],
5903 cx,
5904 )
5905 .unwrap();
5906 view.newline(&Newline, cx);
5907
5908 assert_eq!(
5909 view.buffer().read(cx).read(cx).text(),
5910 concat!(
5911 "{ \n", // Suppress rustfmt
5912 "\n", //
5913 "}\n", //
5914 " x\n", //
5915 " /* \n", //
5916 " \n", //
5917 " */\n", //
5918 "x\n", //
5919 "{{} \n", //
5920 "}\n", //
5921 )
5922 );
5923 });
5924 }
5925
5926 impl Editor {
5927 fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
5928 &self,
5929 cx: &mut MutableAppContext,
5930 ) -> Vec<Range<D>> {
5931 self.local_selections::<D>(cx)
5932 .iter()
5933 .map(|s| {
5934 if s.reversed {
5935 s.end.clone()..s.start.clone()
5936 } else {
5937 s.start.clone()..s.end.clone()
5938 }
5939 })
5940 .collect()
5941 }
5942
5943 fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
5944 let display_map = self
5945 .display_map
5946 .update(cx, |display_map, cx| display_map.snapshot(cx));
5947 self.selections
5948 .iter()
5949 .chain(
5950 self.pending_selection
5951 .as_ref()
5952 .map(|pending| &pending.selection),
5953 )
5954 .map(|s| {
5955 if s.reversed {
5956 s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
5957 } else {
5958 s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
5959 }
5960 })
5961 .collect()
5962 }
5963 }
5964
5965 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
5966 let point = DisplayPoint::new(row as u32, column as u32);
5967 point..point
5968 }
5969
5970 fn build_editor(
5971 buffer: ModelHandle<MultiBuffer>,
5972 settings: EditorSettings,
5973 cx: &mut ViewContext<Editor>,
5974 ) -> Editor {
5975 Editor::for_buffer(buffer, move |_| settings.clone(), cx)
5976 }
5977}
5978
5979trait RangeExt<T> {
5980 fn sorted(&self) -> Range<T>;
5981 fn to_inclusive(&self) -> RangeInclusive<T>;
5982}
5983
5984impl<T: Ord + Clone> RangeExt<T> for Range<T> {
5985 fn sorted(&self) -> Self {
5986 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
5987 }
5988
5989 fn to_inclusive(&self) -> RangeInclusive<T> {
5990 self.start.clone()..=self.end.clone()
5991 }
5992}