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