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