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