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