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