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