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