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 let selections = self.local_selections::<Point>(cx);
1787 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1788 let buffer = self.buffer.read(cx).snapshot(cx);
1789
1790 let mut edits = Vec::new();
1791 let mut new_selection_ranges = Vec::new();
1792 let mut old_folds = Vec::new();
1793 let mut new_folds = Vec::new();
1794
1795 let mut selections = selections.iter().peekable();
1796 let mut contiguous_selections = Vec::new();
1797 while let Some(selection) = selections.next() {
1798 // Accumulate contiguous regions of rows that we want to move.
1799 contiguous_selections.push(selection.point_range(&buffer));
1800
1801 let SpannedRows {
1802 mut buffer_rows,
1803 mut display_rows,
1804 } = selection.spanned_rows(false, &display_map);
1805
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 if buffer.range_contains_excerpt_boundary(start..next_row_buffer_end_offset) {
1833 new_selection_ranges.extend(contiguous_selections.drain(..));
1834 continue;
1835 }
1836
1837 let mut text = String::new();
1838 text.push('\n');
1839 text.extend(buffer.text_for_range(start..end));
1840 edits.push((start..end + 1, String::new()));
1841 edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1842
1843 // Move selections down.
1844 let display_row_delta = next_row_display_end.row() - display_rows.end + 1;
1845 for range in &mut contiguous_selections {
1846 range.start.row += display_row_delta;
1847 range.end.row += display_row_delta;
1848 }
1849
1850 // Move folds down.
1851 old_folds.push(start..end);
1852 let buffer_row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1853 for fold in display_map.folds_in_range(start..end) {
1854 let mut start = fold.start.to_point(&buffer);
1855 let mut end = fold.end.to_point(&buffer);
1856 start.row += buffer_row_delta;
1857 end.row += buffer_row_delta;
1858 new_folds.push(start..end);
1859 }
1860 }
1861
1862 new_selection_ranges.extend(contiguous_selections.drain(..));
1863 }
1864
1865 self.start_transaction(cx);
1866 self.unfold_ranges(old_folds, cx);
1867 self.buffer.update(cx, |buffer, cx| {
1868 for (range, text) in edits.into_iter().rev() {
1869 buffer.edit(Some(range), text, cx);
1870 }
1871 });
1872 self.fold_ranges(new_folds, cx);
1873 self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1874 self.end_transaction(cx);
1875 }
1876
1877 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1878 self.start_transaction(cx);
1879 let mut text = String::new();
1880 let mut selections = self.local_selections::<Point>(cx);
1881 let mut clipboard_selections = Vec::with_capacity(selections.len());
1882 {
1883 let buffer = self.buffer.read(cx).read(cx);
1884 let max_point = buffer.max_point();
1885 for selection in &mut selections {
1886 let is_entire_line = selection.is_empty();
1887 if is_entire_line {
1888 selection.start = Point::new(selection.start.row, 0);
1889 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
1890 }
1891 let mut len = 0;
1892 for chunk in buffer.text_for_range(selection.start..selection.end) {
1893 text.push_str(chunk);
1894 len += chunk.len();
1895 }
1896 clipboard_selections.push(ClipboardSelection {
1897 len,
1898 is_entire_line,
1899 });
1900 }
1901 }
1902 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1903 self.insert("", cx);
1904 self.end_transaction(cx);
1905
1906 cx.as_mut()
1907 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1908 }
1909
1910 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1911 let selections = self.local_selections::<Point>(cx);
1912 let mut text = String::new();
1913 let mut clipboard_selections = Vec::with_capacity(selections.len());
1914 {
1915 let buffer = self.buffer.read(cx).read(cx);
1916 let max_point = buffer.max_point();
1917 for selection in selections.iter() {
1918 let mut start = selection.start;
1919 let mut end = selection.end;
1920 let is_entire_line = selection.is_empty();
1921 if is_entire_line {
1922 start = Point::new(start.row, 0);
1923 end = cmp::min(max_point, Point::new(start.row + 1, 0));
1924 }
1925 let mut len = 0;
1926 for chunk in buffer.text_for_range(start..end) {
1927 text.push_str(chunk);
1928 len += chunk.len();
1929 }
1930 clipboard_selections.push(ClipboardSelection {
1931 len,
1932 is_entire_line,
1933 });
1934 }
1935 }
1936
1937 cx.as_mut()
1938 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1939 }
1940
1941 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1942 if let Some(item) = cx.as_mut().read_from_clipboard() {
1943 let clipboard_text = item.text();
1944 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1945 let mut selections = self.local_selections::<usize>(cx);
1946 let all_selections_were_entire_line =
1947 clipboard_selections.iter().all(|s| s.is_entire_line);
1948 if clipboard_selections.len() != selections.len() {
1949 clipboard_selections.clear();
1950 }
1951
1952 let mut delta = 0_isize;
1953 let mut start_offset = 0;
1954 for (i, selection) in selections.iter_mut().enumerate() {
1955 let to_insert;
1956 let entire_line;
1957 if let Some(clipboard_selection) = clipboard_selections.get(i) {
1958 let end_offset = start_offset + clipboard_selection.len;
1959 to_insert = &clipboard_text[start_offset..end_offset];
1960 entire_line = clipboard_selection.is_entire_line;
1961 start_offset = end_offset
1962 } else {
1963 to_insert = clipboard_text.as_str();
1964 entire_line = all_selections_were_entire_line;
1965 }
1966
1967 selection.start = (selection.start as isize + delta) as usize;
1968 selection.end = (selection.end as isize + delta) as usize;
1969
1970 self.buffer.update(cx, |buffer, cx| {
1971 // If the corresponding selection was empty when this slice of the
1972 // clipboard text was written, then the entire line containing the
1973 // selection was copied. If this selection is also currently empty,
1974 // then paste the line before the current line of the buffer.
1975 let range = if selection.is_empty() && entire_line {
1976 let column = selection.start.to_point(&buffer.read(cx)).column as usize;
1977 let line_start = selection.start - column;
1978 line_start..line_start
1979 } else {
1980 selection.start..selection.end
1981 };
1982
1983 delta += to_insert.len() as isize - range.len() as isize;
1984 buffer.edit([range], to_insert, cx);
1985 selection.start += to_insert.len();
1986 selection.end = selection.start;
1987 });
1988 }
1989 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1990 } else {
1991 self.insert(clipboard_text, cx);
1992 }
1993 }
1994 }
1995
1996 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1997 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
1998 if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
1999 self.set_selections(selections, cx);
2000 }
2001 self.request_autoscroll(Autoscroll::Fit, cx);
2002 }
2003 }
2004
2005 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
2006 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
2007 if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
2008 self.set_selections(selections, cx);
2009 }
2010 self.request_autoscroll(Autoscroll::Fit, cx);
2011 }
2012 }
2013
2014 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
2015 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2016 let mut selections = self.local_selections::<Point>(cx);
2017 for selection in &mut selections {
2018 let start = selection.start.to_display_point(&display_map);
2019 let end = selection.end.to_display_point(&display_map);
2020
2021 if start != end {
2022 selection.end = selection.start.clone();
2023 } else {
2024 let cursor = movement::left(&display_map, start)
2025 .unwrap()
2026 .to_point(&display_map);
2027 selection.start = cursor.clone();
2028 selection.end = cursor;
2029 }
2030 selection.reversed = false;
2031 selection.goal = SelectionGoal::None;
2032 }
2033 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2034 }
2035
2036 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2037 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2038 let mut selections = self.local_selections::<Point>(cx);
2039 for selection in &mut selections {
2040 let head = selection.head().to_display_point(&display_map);
2041 let cursor = movement::left(&display_map, head)
2042 .unwrap()
2043 .to_point(&display_map);
2044 selection.set_head(cursor);
2045 selection.goal = SelectionGoal::None;
2046 }
2047 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2048 }
2049
2050 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2051 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2052 let mut selections = self.local_selections::<Point>(cx);
2053 for selection in &mut selections {
2054 let start = selection.start.to_display_point(&display_map);
2055 let end = selection.end.to_display_point(&display_map);
2056
2057 if start != end {
2058 selection.start = selection.end.clone();
2059 } else {
2060 let cursor = movement::right(&display_map, end)
2061 .unwrap()
2062 .to_point(&display_map);
2063 selection.start = cursor;
2064 selection.end = cursor;
2065 }
2066 selection.reversed = false;
2067 selection.goal = SelectionGoal::None;
2068 }
2069 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2070 }
2071
2072 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2073 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2074 let mut selections = self.local_selections::<Point>(cx);
2075 for selection in &mut selections {
2076 let head = selection.head().to_display_point(&display_map);
2077 let cursor = movement::right(&display_map, head)
2078 .unwrap()
2079 .to_point(&display_map);
2080 selection.set_head(cursor);
2081 selection.goal = SelectionGoal::None;
2082 }
2083 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2084 }
2085
2086 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2087 if matches!(self.mode, EditorMode::SingleLine) {
2088 cx.propagate_action();
2089 return;
2090 }
2091
2092 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2093 let mut selections = self.local_selections::<Point>(cx);
2094 for selection in &mut selections {
2095 let start = selection.start.to_display_point(&display_map);
2096 let end = selection.end.to_display_point(&display_map);
2097 if start != end {
2098 selection.goal = SelectionGoal::None;
2099 }
2100
2101 let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
2102 let cursor = start.to_point(&display_map);
2103 selection.start = cursor;
2104 selection.end = cursor;
2105 selection.goal = goal;
2106 selection.reversed = false;
2107 }
2108 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2109 }
2110
2111 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
2112 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2113 let mut selections = self.local_selections::<Point>(cx);
2114 for selection in &mut selections {
2115 let head = selection.head().to_display_point(&display_map);
2116 let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
2117 let cursor = head.to_point(&display_map);
2118 selection.set_head(cursor);
2119 selection.goal = goal;
2120 }
2121 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2122 }
2123
2124 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2125 if matches!(self.mode, EditorMode::SingleLine) {
2126 cx.propagate_action();
2127 return;
2128 }
2129
2130 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2131 let mut selections = self.local_selections::<Point>(cx);
2132 for selection in &mut selections {
2133 let start = selection.start.to_display_point(&display_map);
2134 let end = selection.end.to_display_point(&display_map);
2135 if start != end {
2136 selection.goal = SelectionGoal::None;
2137 }
2138
2139 let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
2140 let cursor = start.to_point(&display_map);
2141 selection.start = cursor;
2142 selection.end = cursor;
2143 selection.goal = goal;
2144 selection.reversed = false;
2145 }
2146 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2147 }
2148
2149 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
2150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2151 let mut selections = self.local_selections::<Point>(cx);
2152 for selection in &mut selections {
2153 let head = selection.head().to_display_point(&display_map);
2154 let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
2155 let cursor = head.to_point(&display_map);
2156 selection.set_head(cursor);
2157 selection.goal = goal;
2158 }
2159 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2160 }
2161
2162 pub fn move_to_previous_word_boundary(
2163 &mut self,
2164 _: &MoveToPreviousWordBoundary,
2165 cx: &mut ViewContext<Self>,
2166 ) {
2167 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2168 let mut selections = self.local_selections::<Point>(cx);
2169 for selection in &mut selections {
2170 let head = selection.head().to_display_point(&display_map);
2171 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2172 selection.start = cursor.clone();
2173 selection.end = cursor;
2174 selection.reversed = false;
2175 selection.goal = SelectionGoal::None;
2176 }
2177 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2178 }
2179
2180 pub fn select_to_previous_word_boundary(
2181 &mut self,
2182 _: &SelectToPreviousWordBoundary,
2183 cx: &mut ViewContext<Self>,
2184 ) {
2185 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2186 let mut selections = self.local_selections::<Point>(cx);
2187 for selection in &mut selections {
2188 let head = selection.head().to_display_point(&display_map);
2189 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2190 selection.set_head(cursor);
2191 selection.goal = SelectionGoal::None;
2192 }
2193 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2194 }
2195
2196 pub fn delete_to_previous_word_boundary(
2197 &mut self,
2198 _: &DeleteToPreviousWordBoundary,
2199 cx: &mut ViewContext<Self>,
2200 ) {
2201 self.start_transaction(cx);
2202 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2203 let mut selections = self.local_selections::<Point>(cx);
2204 for selection in &mut selections {
2205 if selection.is_empty() {
2206 let head = selection.head().to_display_point(&display_map);
2207 let cursor =
2208 movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2209 selection.set_head(cursor);
2210 selection.goal = SelectionGoal::None;
2211 }
2212 }
2213 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2214 self.insert("", cx);
2215 self.end_transaction(cx);
2216 }
2217
2218 pub fn move_to_next_word_boundary(
2219 &mut self,
2220 _: &MoveToNextWordBoundary,
2221 cx: &mut ViewContext<Self>,
2222 ) {
2223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2224 let mut selections = self.local_selections::<Point>(cx);
2225 for selection in &mut selections {
2226 let head = selection.head().to_display_point(&display_map);
2227 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2228 selection.start = cursor;
2229 selection.end = cursor;
2230 selection.reversed = false;
2231 selection.goal = SelectionGoal::None;
2232 }
2233 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2234 }
2235
2236 pub fn select_to_next_word_boundary(
2237 &mut self,
2238 _: &SelectToNextWordBoundary,
2239 cx: &mut ViewContext<Self>,
2240 ) {
2241 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2242 let mut selections = self.local_selections::<Point>(cx);
2243 for selection in &mut selections {
2244 let head = selection.head().to_display_point(&display_map);
2245 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2246 selection.set_head(cursor);
2247 selection.goal = SelectionGoal::None;
2248 }
2249 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2250 }
2251
2252 pub fn delete_to_next_word_boundary(
2253 &mut self,
2254 _: &DeleteToNextWordBoundary,
2255 cx: &mut ViewContext<Self>,
2256 ) {
2257 self.start_transaction(cx);
2258 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2259 let mut selections = self.local_selections::<Point>(cx);
2260 for selection in &mut selections {
2261 if selection.is_empty() {
2262 let head = selection.head().to_display_point(&display_map);
2263 let cursor =
2264 movement::next_word_boundary(&display_map, head).to_point(&display_map);
2265 selection.set_head(cursor);
2266 selection.goal = SelectionGoal::None;
2267 }
2268 }
2269 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2270 self.insert("", cx);
2271 self.end_transaction(cx);
2272 }
2273
2274 pub fn move_to_beginning_of_line(
2275 &mut self,
2276 _: &MoveToBeginningOfLine,
2277 cx: &mut ViewContext<Self>,
2278 ) {
2279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2280 let mut selections = self.local_selections::<Point>(cx);
2281 for selection in &mut selections {
2282 let head = selection.head().to_display_point(&display_map);
2283 let new_head = movement::line_beginning(&display_map, head, true);
2284 let cursor = new_head.to_point(&display_map);
2285 selection.start = cursor;
2286 selection.end = cursor;
2287 selection.reversed = false;
2288 selection.goal = SelectionGoal::None;
2289 }
2290 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2291 }
2292
2293 pub fn select_to_beginning_of_line(
2294 &mut self,
2295 SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
2296 cx: &mut ViewContext<Self>,
2297 ) {
2298 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2299 let mut selections = self.local_selections::<Point>(cx);
2300 for selection in &mut selections {
2301 let head = selection.head().to_display_point(&display_map);
2302 let new_head = movement::line_beginning(&display_map, head, *toggle_indent);
2303 selection.set_head(new_head.to_point(&display_map));
2304 selection.goal = SelectionGoal::None;
2305 }
2306 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2307 }
2308
2309 pub fn delete_to_beginning_of_line(
2310 &mut self,
2311 _: &DeleteToBeginningOfLine,
2312 cx: &mut ViewContext<Self>,
2313 ) {
2314 self.start_transaction(cx);
2315 self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
2316 self.backspace(&Backspace, cx);
2317 self.end_transaction(cx);
2318 }
2319
2320 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
2321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2322 let mut selections = self.local_selections::<Point>(cx);
2323 {
2324 for selection in &mut selections {
2325 let head = selection.head().to_display_point(&display_map);
2326 let new_head = movement::line_end(&display_map, head);
2327 let anchor = new_head.to_point(&display_map);
2328 selection.start = anchor.clone();
2329 selection.end = anchor;
2330 selection.reversed = false;
2331 selection.goal = SelectionGoal::None;
2332 }
2333 }
2334 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2335 }
2336
2337 pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2338 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2339 let mut selections = self.local_selections::<Point>(cx);
2340 for selection in &mut selections {
2341 let head = selection.head().to_display_point(&display_map);
2342 let new_head = movement::line_end(&display_map, head);
2343 selection.set_head(new_head.to_point(&display_map));
2344 selection.goal = SelectionGoal::None;
2345 }
2346 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2347 }
2348
2349 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2350 self.start_transaction(cx);
2351 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2352 self.delete(&Delete, cx);
2353 self.end_transaction(cx);
2354 }
2355
2356 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2357 self.start_transaction(cx);
2358 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2359 self.cut(&Cut, cx);
2360 self.end_transaction(cx);
2361 }
2362
2363 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2364 let selection = Selection {
2365 id: post_inc(&mut self.next_selection_id),
2366 start: 0,
2367 end: 0,
2368 reversed: false,
2369 goal: SelectionGoal::None,
2370 };
2371 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2372 }
2373
2374 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
2375 let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
2376 selection.set_head(Point::zero());
2377 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2378 }
2379
2380 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
2381 let cursor = self.buffer.read(cx).read(cx).len();
2382 let selection = Selection {
2383 id: post_inc(&mut self.next_selection_id),
2384 start: cursor,
2385 end: cursor,
2386 reversed: false,
2387 goal: SelectionGoal::None,
2388 };
2389 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2390 }
2391
2392 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
2393 let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
2394 selection.set_head(self.buffer.read(cx).read(cx).len());
2395 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2396 }
2397
2398 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
2399 let selection = Selection {
2400 id: post_inc(&mut self.next_selection_id),
2401 start: 0,
2402 end: self.buffer.read(cx).read(cx).len(),
2403 reversed: false,
2404 goal: SelectionGoal::None,
2405 };
2406 self.update_selections(vec![selection], None, cx);
2407 }
2408
2409 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
2410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2411 let mut selections = self.local_selections::<Point>(cx);
2412 let max_point = display_map.buffer_snapshot.max_point();
2413 for selection in &mut selections {
2414 let rows = selection.spanned_rows(true, &display_map).buffer_rows;
2415 selection.start = Point::new(rows.start, 0);
2416 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
2417 selection.reversed = false;
2418 }
2419 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2420 }
2421
2422 pub fn split_selection_into_lines(
2423 &mut self,
2424 _: &SplitSelectionIntoLines,
2425 cx: &mut ViewContext<Self>,
2426 ) {
2427 let mut to_unfold = Vec::new();
2428 let mut new_selections = Vec::new();
2429 {
2430 let selections = self.local_selections::<Point>(cx);
2431 let buffer = self.buffer.read(cx).read(cx);
2432 for selection in selections {
2433 for row in selection.start.row..selection.end.row {
2434 let cursor = Point::new(row, buffer.line_len(row));
2435 new_selections.push(Selection {
2436 id: post_inc(&mut self.next_selection_id),
2437 start: cursor,
2438 end: cursor,
2439 reversed: false,
2440 goal: SelectionGoal::None,
2441 });
2442 }
2443 new_selections.push(Selection {
2444 id: selection.id,
2445 start: selection.end,
2446 end: selection.end,
2447 reversed: false,
2448 goal: SelectionGoal::None,
2449 });
2450 to_unfold.push(selection.start..selection.end);
2451 }
2452 }
2453 self.unfold_ranges(to_unfold, cx);
2454 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2455 }
2456
2457 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2458 self.add_selection(true, cx);
2459 }
2460
2461 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2462 self.add_selection(false, cx);
2463 }
2464
2465 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2467 let mut selections = self.local_selections::<Point>(cx);
2468 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2469 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2470 let range = oldest_selection.display_range(&display_map).sorted();
2471 let columns = cmp::min(range.start.column(), range.end.column())
2472 ..cmp::max(range.start.column(), range.end.column());
2473
2474 selections.clear();
2475 let mut stack = Vec::new();
2476 for row in range.start.row()..=range.end.row() {
2477 if let Some(selection) = self.build_columnar_selection(
2478 &display_map,
2479 row,
2480 &columns,
2481 oldest_selection.reversed,
2482 ) {
2483 stack.push(selection.id);
2484 selections.push(selection);
2485 }
2486 }
2487
2488 if above {
2489 stack.reverse();
2490 }
2491
2492 AddSelectionsState { above, stack }
2493 });
2494
2495 let last_added_selection = *state.stack.last().unwrap();
2496 let mut new_selections = Vec::new();
2497 if above == state.above {
2498 let end_row = if above {
2499 0
2500 } else {
2501 display_map.max_point().row()
2502 };
2503
2504 'outer: for selection in selections {
2505 if selection.id == last_added_selection {
2506 let range = selection.display_range(&display_map).sorted();
2507 debug_assert_eq!(range.start.row(), range.end.row());
2508 let mut row = range.start.row();
2509 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2510 {
2511 start..end
2512 } else {
2513 cmp::min(range.start.column(), range.end.column())
2514 ..cmp::max(range.start.column(), range.end.column())
2515 };
2516
2517 while row != end_row {
2518 if above {
2519 row -= 1;
2520 } else {
2521 row += 1;
2522 }
2523
2524 if let Some(new_selection) = self.build_columnar_selection(
2525 &display_map,
2526 row,
2527 &columns,
2528 selection.reversed,
2529 ) {
2530 state.stack.push(new_selection.id);
2531 if above {
2532 new_selections.push(new_selection);
2533 new_selections.push(selection);
2534 } else {
2535 new_selections.push(selection);
2536 new_selections.push(new_selection);
2537 }
2538
2539 continue 'outer;
2540 }
2541 }
2542 }
2543
2544 new_selections.push(selection);
2545 }
2546 } else {
2547 new_selections = selections;
2548 new_selections.retain(|s| s.id != last_added_selection);
2549 state.stack.pop();
2550 }
2551
2552 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2553 if state.stack.len() > 1 {
2554 self.add_selections_state = Some(state);
2555 }
2556 }
2557
2558 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
2559 let replace_newest = action.0;
2560 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2561 let buffer = &display_map.buffer_snapshot;
2562 let mut selections = self.local_selections::<usize>(cx);
2563 if let Some(mut select_next_state) = self.select_next_state.take() {
2564 let query = &select_next_state.query;
2565 if !select_next_state.done {
2566 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
2567 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
2568 let mut next_selected_range = None;
2569
2570 let bytes_after_last_selection =
2571 buffer.bytes_in_range(last_selection.end..buffer.len());
2572 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
2573 let query_matches = query
2574 .stream_find_iter(bytes_after_last_selection)
2575 .map(|result| (last_selection.end, result))
2576 .chain(
2577 query
2578 .stream_find_iter(bytes_before_first_selection)
2579 .map(|result| (0, result)),
2580 );
2581 for (start_offset, query_match) in query_matches {
2582 let query_match = query_match.unwrap(); // can only fail due to I/O
2583 let offset_range =
2584 start_offset + query_match.start()..start_offset + query_match.end();
2585 let display_range = offset_range.start.to_display_point(&display_map)
2586 ..offset_range.end.to_display_point(&display_map);
2587
2588 if !select_next_state.wordwise
2589 || (!movement::is_inside_word(&display_map, display_range.start)
2590 && !movement::is_inside_word(&display_map, display_range.end))
2591 {
2592 next_selected_range = Some(offset_range);
2593 break;
2594 }
2595 }
2596
2597 if let Some(next_selected_range) = next_selected_range {
2598 if replace_newest {
2599 if let Some(newest_id) =
2600 selections.iter().max_by_key(|s| s.id).map(|s| s.id)
2601 {
2602 selections.retain(|s| s.id != newest_id);
2603 }
2604 }
2605 selections.push(Selection {
2606 id: post_inc(&mut self.next_selection_id),
2607 start: next_selected_range.start,
2608 end: next_selected_range.end,
2609 reversed: false,
2610 goal: SelectionGoal::None,
2611 });
2612 selections.sort_unstable_by_key(|s| s.start);
2613 self.update_selections(selections, Some(Autoscroll::Newest), cx);
2614 } else {
2615 select_next_state.done = true;
2616 }
2617 }
2618
2619 self.select_next_state = Some(select_next_state);
2620 } else if selections.len() == 1 {
2621 let selection = selections.last_mut().unwrap();
2622 if selection.start == selection.end {
2623 let word_range = movement::surrounding_word(
2624 &display_map,
2625 selection.start.to_display_point(&display_map),
2626 );
2627 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
2628 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
2629 selection.goal = SelectionGoal::None;
2630 selection.reversed = false;
2631
2632 let query = buffer
2633 .text_for_range(selection.start..selection.end)
2634 .collect::<String>();
2635 let select_state = SelectNextState {
2636 query: AhoCorasick::new_auto_configured(&[query]),
2637 wordwise: true,
2638 done: false,
2639 };
2640 self.update_selections(selections, Some(Autoscroll::Newest), cx);
2641 self.select_next_state = Some(select_state);
2642 } else {
2643 let query = buffer
2644 .text_for_range(selection.start..selection.end)
2645 .collect::<String>();
2646 self.select_next_state = Some(SelectNextState {
2647 query: AhoCorasick::new_auto_configured(&[query]),
2648 wordwise: false,
2649 done: false,
2650 });
2651 self.select_next(action, cx);
2652 }
2653 }
2654 }
2655
2656 pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
2657 // Get the line comment prefix. Split its trailing whitespace into a separate string,
2658 // as that portion won't be used for detecting if a line is a comment.
2659 let full_comment_prefix =
2660 if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
2661 prefix.to_string()
2662 } else {
2663 return;
2664 };
2665 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
2666 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
2667
2668 self.start_transaction(cx);
2669 let mut selections = self.local_selections::<Point>(cx);
2670 let mut all_selection_lines_are_comments = true;
2671 let mut edit_ranges = Vec::new();
2672 let mut last_toggled_row = None;
2673 self.buffer.update(cx, |buffer, cx| {
2674 for selection in &mut selections {
2675 edit_ranges.clear();
2676 let snapshot = buffer.snapshot(cx);
2677
2678 let end_row =
2679 if selection.end.row > selection.start.row && selection.end.column == 0 {
2680 selection.end.row
2681 } else {
2682 selection.end.row + 1
2683 };
2684
2685 for row in selection.start.row..end_row {
2686 // If multiple selections contain a given row, avoid processing that
2687 // row more than once.
2688 if last_toggled_row == Some(row) {
2689 continue;
2690 } else {
2691 last_toggled_row = Some(row);
2692 }
2693
2694 if snapshot.is_line_blank(row) {
2695 continue;
2696 }
2697
2698 let start = Point::new(row, snapshot.indent_column_for_line(row));
2699 let mut line_bytes = snapshot
2700 .bytes_in_range(start..snapshot.max_point())
2701 .flatten()
2702 .copied();
2703
2704 // If this line currently begins with the line comment prefix, then record
2705 // the range containing the prefix.
2706 if all_selection_lines_are_comments
2707 && line_bytes
2708 .by_ref()
2709 .take(comment_prefix.len())
2710 .eq(comment_prefix.bytes())
2711 {
2712 // Include any whitespace that matches the comment prefix.
2713 let matching_whitespace_len = line_bytes
2714 .zip(comment_prefix_whitespace.bytes())
2715 .take_while(|(a, b)| a == b)
2716 .count() as u32;
2717 let end = Point::new(
2718 row,
2719 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
2720 );
2721 edit_ranges.push(start..end);
2722 }
2723 // If this line does not begin with the line comment prefix, then record
2724 // the position where the prefix should be inserted.
2725 else {
2726 all_selection_lines_are_comments = false;
2727 edit_ranges.push(start..start);
2728 }
2729 }
2730
2731 if !edit_ranges.is_empty() {
2732 if all_selection_lines_are_comments {
2733 buffer.edit(edit_ranges.iter().cloned(), "", cx);
2734 } else {
2735 let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
2736 let edit_ranges = edit_ranges.iter().map(|range| {
2737 let position = Point::new(range.start.row, min_column);
2738 position..position
2739 });
2740 buffer.edit(edit_ranges, &full_comment_prefix, cx);
2741 }
2742 }
2743 }
2744 });
2745
2746 self.update_selections(
2747 self.local_selections::<usize>(cx),
2748 Some(Autoscroll::Fit),
2749 cx,
2750 );
2751 self.end_transaction(cx);
2752 }
2753
2754 pub fn select_larger_syntax_node(
2755 &mut self,
2756 _: &SelectLargerSyntaxNode,
2757 cx: &mut ViewContext<Self>,
2758 ) {
2759 let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
2760 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2761 let buffer = self.buffer.read(cx).snapshot(cx);
2762
2763 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2764 let mut selected_larger_node = false;
2765 let mut new_selections = old_selections
2766 .iter()
2767 .map(|selection| {
2768 let old_range = selection.start..selection.end;
2769 let mut new_range = old_range.clone();
2770 while let Some(containing_range) =
2771 buffer.range_for_syntax_ancestor(new_range.clone())
2772 {
2773 new_range = containing_range;
2774 if !display_map.intersects_fold(new_range.start)
2775 && !display_map.intersects_fold(new_range.end)
2776 {
2777 break;
2778 }
2779 }
2780
2781 selected_larger_node |= new_range != old_range;
2782 Selection {
2783 id: selection.id,
2784 start: new_range.start,
2785 end: new_range.end,
2786 goal: SelectionGoal::None,
2787 reversed: selection.reversed,
2788 }
2789 })
2790 .collect::<Vec<_>>();
2791
2792 if selected_larger_node {
2793 stack.push(old_selections);
2794 new_selections.sort_unstable_by_key(|selection| selection.start);
2795 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2796 }
2797 self.select_larger_syntax_node_stack = stack;
2798 }
2799
2800 pub fn select_smaller_syntax_node(
2801 &mut self,
2802 _: &SelectSmallerSyntaxNode,
2803 cx: &mut ViewContext<Self>,
2804 ) {
2805 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2806 if let Some(selections) = stack.pop() {
2807 self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
2808 }
2809 self.select_larger_syntax_node_stack = stack;
2810 }
2811
2812 pub fn move_to_enclosing_bracket(
2813 &mut self,
2814 _: &MoveToEnclosingBracket,
2815 cx: &mut ViewContext<Self>,
2816 ) {
2817 let mut selections = self.local_selections::<usize>(cx);
2818 let buffer = self.buffer.read(cx).snapshot(cx);
2819 for selection in &mut selections {
2820 if let Some((open_range, close_range)) =
2821 buffer.enclosing_bracket_ranges(selection.start..selection.end)
2822 {
2823 let close_range = close_range.to_inclusive();
2824 let destination = if close_range.contains(&selection.start)
2825 && close_range.contains(&selection.end)
2826 {
2827 open_range.end
2828 } else {
2829 *close_range.start()
2830 };
2831 selection.start = destination;
2832 selection.end = destination;
2833 }
2834 }
2835
2836 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2837 }
2838
2839 pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
2840 let buffer = self.buffer.read(cx).snapshot(cx);
2841 let selection = self.newest_selection::<usize>(&buffer);
2842 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
2843 active_diagnostics
2844 .primary_range
2845 .to_offset(&buffer)
2846 .to_inclusive()
2847 });
2848 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
2849 if active_primary_range.contains(&selection.head()) {
2850 *active_primary_range.end()
2851 } else {
2852 selection.head()
2853 }
2854 } else {
2855 selection.head()
2856 };
2857
2858 loop {
2859 let next_group = buffer
2860 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
2861 .find_map(|(provider_name, entry)| {
2862 if entry.diagnostic.is_primary
2863 && !entry.range.is_empty()
2864 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
2865 {
2866 Some((provider_name, entry.range, entry.diagnostic.group_id))
2867 } else {
2868 None
2869 }
2870 });
2871
2872 if let Some((provider_name, primary_range, group_id)) = next_group {
2873 self.activate_diagnostics(provider_name, group_id, cx);
2874 self.update_selections(
2875 vec![Selection {
2876 id: selection.id,
2877 start: primary_range.start,
2878 end: primary_range.start,
2879 reversed: false,
2880 goal: SelectionGoal::None,
2881 }],
2882 Some(Autoscroll::Center),
2883 cx,
2884 );
2885 break;
2886 } else if search_start == 0 {
2887 break;
2888 } else {
2889 // Cycle around to the start of the buffer.
2890 search_start = 0;
2891 }
2892 }
2893 }
2894
2895 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
2896 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
2897 let buffer = self.buffer.read(cx).snapshot(cx);
2898 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
2899 let is_valid = buffer
2900 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
2901 .any(|(_, entry)| {
2902 entry.diagnostic.is_primary
2903 && !entry.range.is_empty()
2904 && entry.range.start == primary_range_start
2905 && entry.diagnostic.message == active_diagnostics.primary_message
2906 });
2907
2908 if is_valid != active_diagnostics.is_valid {
2909 active_diagnostics.is_valid = is_valid;
2910 let mut new_styles = HashMap::default();
2911 for (block_id, diagnostic) in &active_diagnostics.blocks {
2912 new_styles.insert(
2913 *block_id,
2914 diagnostic_block_renderer(
2915 diagnostic.clone(),
2916 is_valid,
2917 self.build_settings.clone(),
2918 ),
2919 );
2920 }
2921 self.display_map
2922 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
2923 }
2924 }
2925 }
2926
2927 fn activate_diagnostics(
2928 &mut self,
2929 provider_name: &str,
2930 group_id: usize,
2931 cx: &mut ViewContext<Self>,
2932 ) {
2933 self.dismiss_diagnostics(cx);
2934 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
2935 let buffer = self.buffer.read(cx).snapshot(cx);
2936
2937 let mut primary_range = None;
2938 let mut primary_message = None;
2939 let mut group_end = Point::zero();
2940 let diagnostic_group = buffer
2941 .diagnostic_group::<Point>(provider_name, group_id)
2942 .map(|entry| {
2943 if entry.range.end > group_end {
2944 group_end = entry.range.end;
2945 }
2946 if entry.diagnostic.is_primary {
2947 primary_range = Some(entry.range.clone());
2948 primary_message = Some(entry.diagnostic.message.clone());
2949 }
2950 entry
2951 })
2952 .collect::<Vec<_>>();
2953 let primary_range = primary_range.unwrap();
2954 let primary_message = primary_message.unwrap();
2955 let primary_range =
2956 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
2957
2958 let blocks = display_map
2959 .insert_blocks(
2960 diagnostic_group.iter().map(|entry| {
2961 let build_settings = self.build_settings.clone();
2962 let diagnostic = entry.diagnostic.clone();
2963 let message_height = diagnostic.message.lines().count() as u8;
2964
2965 BlockProperties {
2966 position: entry.range.start,
2967 height: message_height,
2968 render: diagnostic_block_renderer(diagnostic, true, build_settings),
2969 disposition: BlockDisposition::Below,
2970 }
2971 }),
2972 cx,
2973 )
2974 .into_iter()
2975 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
2976 .collect();
2977
2978 Some(ActiveDiagnosticGroup {
2979 primary_range,
2980 primary_message,
2981 blocks,
2982 is_valid: true,
2983 })
2984 });
2985 }
2986
2987 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
2988 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
2989 self.display_map.update(cx, |display_map, cx| {
2990 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
2991 });
2992 cx.notify();
2993 }
2994 }
2995
2996 fn build_columnar_selection(
2997 &mut self,
2998 display_map: &DisplaySnapshot,
2999 row: u32,
3000 columns: &Range<u32>,
3001 reversed: bool,
3002 ) -> Option<Selection<Point>> {
3003 let is_empty = columns.start == columns.end;
3004 let line_len = display_map.line_len(row);
3005 if columns.start < line_len || (is_empty && columns.start == line_len) {
3006 let start = DisplayPoint::new(row, columns.start);
3007 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
3008 Some(Selection {
3009 id: post_inc(&mut self.next_selection_id),
3010 start: start.to_point(display_map),
3011 end: end.to_point(display_map),
3012 reversed,
3013 goal: SelectionGoal::ColumnRange {
3014 start: columns.start,
3015 end: columns.end,
3016 },
3017 })
3018 } else {
3019 None
3020 }
3021 }
3022
3023 pub fn visible_selections<'a>(
3024 &'a self,
3025 display_rows: Range<u32>,
3026 cx: &'a mut MutableAppContext,
3027 ) -> HashMap<ReplicaId, Vec<Selection<DisplayPoint>>> {
3028 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3029 let buffer = &display_map.buffer_snapshot;
3030
3031 let start = if display_rows.start == 0 {
3032 Anchor::min()
3033 } else {
3034 buffer.anchor_before(
3035 DisplayPoint::new(display_rows.start, 0).to_offset(&display_map, Bias::Left),
3036 )
3037 };
3038 let end = if display_rows.end > display_map.max_point().row() {
3039 Anchor::max()
3040 } else {
3041 buffer.anchor_before(
3042 DisplayPoint::new(display_rows.end, 0).to_offset(&display_map, Bias::Right),
3043 )
3044 };
3045
3046 let start_ix = match self
3047 .selections
3048 .binary_search_by(|probe| probe.end.cmp(&start, &buffer).unwrap())
3049 {
3050 Ok(ix) | Err(ix) => ix,
3051 };
3052 let end_ix = match self
3053 .selections
3054 .binary_search_by(|probe| probe.start.cmp(&end, &buffer).unwrap())
3055 {
3056 Ok(ix) => ix + 1,
3057 Err(ix) => ix,
3058 };
3059
3060 fn display_selection(
3061 selection: &Selection<Anchor>,
3062 display_map: &DisplaySnapshot,
3063 ) -> Selection<DisplayPoint> {
3064 Selection {
3065 id: selection.id,
3066 start: selection.start.to_display_point(&display_map),
3067 end: selection.end.to_display_point(&display_map),
3068 reversed: selection.reversed,
3069 goal: selection.goal,
3070 }
3071 }
3072
3073 let mut result = HashMap::default();
3074
3075 result.insert(
3076 self.replica_id(cx),
3077 self.selections[start_ix..end_ix]
3078 .iter()
3079 .chain(
3080 self.pending_selection
3081 .as_ref()
3082 .map(|pending| &pending.selection),
3083 )
3084 .map(|s| display_selection(s, &display_map))
3085 .collect(),
3086 );
3087
3088 for (replica_id, selection) in display_map
3089 .buffer_snapshot
3090 .remote_selections_in_range(&(start..end))
3091 {
3092 result
3093 .entry(replica_id)
3094 .or_insert(Vec::new())
3095 .push(display_selection(&selection, &display_map));
3096 }
3097
3098 result
3099 }
3100
3101 pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3102 where
3103 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3104 {
3105 let buffer = self.buffer.read(cx).snapshot(cx);
3106 let mut selections = self
3107 .resolve_selections::<D, _>(self.selections.iter(), &buffer)
3108 .peekable();
3109
3110 let mut pending_selection = self.pending_selection::<D>(&buffer);
3111
3112 iter::from_fn(move || {
3113 if let Some(pending) = pending_selection.as_mut() {
3114 while let Some(next_selection) = selections.peek() {
3115 if pending.start <= next_selection.end && pending.end >= next_selection.start {
3116 let next_selection = selections.next().unwrap();
3117 if next_selection.start < pending.start {
3118 pending.start = next_selection.start;
3119 }
3120 if next_selection.end > pending.end {
3121 pending.end = next_selection.end;
3122 }
3123 } else if next_selection.end < pending.start {
3124 return selections.next();
3125 } else {
3126 break;
3127 }
3128 }
3129
3130 pending_selection.take()
3131 } else {
3132 selections.next()
3133 }
3134 })
3135 .collect()
3136 }
3137
3138 pub fn local_anchor_selections(&self) -> &Arc<[Selection<Anchor>]> {
3139 &self.selections
3140 }
3141
3142 fn resolve_selections<'a, D, I>(
3143 &self,
3144 selections: I,
3145 snapshot: &MultiBufferSnapshot,
3146 ) -> impl 'a + Iterator<Item = Selection<D>>
3147 where
3148 D: TextDimension + Ord + Sub<D, Output = D>,
3149 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
3150 {
3151 let (to_summarize, selections) = selections.into_iter().tee();
3152 let mut summaries = snapshot
3153 .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
3154 .into_iter();
3155 selections.map(move |s| Selection {
3156 id: s.id,
3157 start: summaries.next().unwrap(),
3158 end: summaries.next().unwrap(),
3159 reversed: s.reversed,
3160 goal: s.goal,
3161 })
3162 }
3163
3164 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3165 &self,
3166 snapshot: &MultiBufferSnapshot,
3167 ) -> Option<Selection<D>> {
3168 self.pending_selection
3169 .as_ref()
3170 .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
3171 }
3172
3173 fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3174 &self,
3175 selection: &Selection<Anchor>,
3176 buffer: &MultiBufferSnapshot,
3177 ) -> Selection<D> {
3178 Selection {
3179 id: selection.id,
3180 start: selection.start.summary::<D>(&buffer),
3181 end: selection.end.summary::<D>(&buffer),
3182 reversed: selection.reversed,
3183 goal: selection.goal,
3184 }
3185 }
3186
3187 fn selection_count<'a>(&self) -> usize {
3188 let mut count = self.selections.len();
3189 if self.pending_selection.is_some() {
3190 count += 1;
3191 }
3192 count
3193 }
3194
3195 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3196 &self,
3197 snapshot: &MultiBufferSnapshot,
3198 ) -> Selection<D> {
3199 self.selections
3200 .iter()
3201 .min_by_key(|s| s.id)
3202 .map(|selection| self.resolve_selection(selection, snapshot))
3203 .or_else(|| self.pending_selection(snapshot))
3204 .unwrap()
3205 }
3206
3207 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3208 &self,
3209 snapshot: &MultiBufferSnapshot,
3210 ) -> Selection<D> {
3211 self.pending_selection(snapshot)
3212 .or_else(|| {
3213 self.selections
3214 .iter()
3215 .max_by_key(|s| s.id)
3216 .map(|selection| self.resolve_selection(selection, snapshot))
3217 })
3218 .unwrap()
3219 }
3220
3221 pub fn update_selections<T>(
3222 &mut self,
3223 mut selections: Vec<Selection<T>>,
3224 autoscroll: Option<Autoscroll>,
3225 cx: &mut ViewContext<Self>,
3226 ) where
3227 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3228 {
3229 // Merge overlapping selections.
3230 let buffer = self.buffer.read(cx).snapshot(cx);
3231 let mut i = 1;
3232 while i < selections.len() {
3233 if selections[i - 1].end >= selections[i].start {
3234 let removed = selections.remove(i);
3235 if removed.start < selections[i - 1].start {
3236 selections[i - 1].start = removed.start;
3237 }
3238 if removed.end > selections[i - 1].end {
3239 selections[i - 1].end = removed.end;
3240 }
3241 } else {
3242 i += 1;
3243 }
3244 }
3245
3246 self.pending_selection = None;
3247 self.add_selections_state = None;
3248 self.select_next_state = None;
3249 self.select_larger_syntax_node_stack.clear();
3250 while let Some(autoclose_pair) = self.autoclose_stack.last() {
3251 let all_selections_inside_autoclose_ranges =
3252 if selections.len() == autoclose_pair.ranges.len() {
3253 selections
3254 .iter()
3255 .zip(autoclose_pair.ranges.iter().map(|r| r.to_point(&buffer)))
3256 .all(|(selection, autoclose_range)| {
3257 let head = selection.head().to_point(&buffer);
3258 autoclose_range.start <= head && autoclose_range.end >= head
3259 })
3260 } else {
3261 false
3262 };
3263
3264 if all_selections_inside_autoclose_ranges {
3265 break;
3266 } else {
3267 self.autoclose_stack.pop();
3268 }
3269 }
3270
3271 if let Some(autoscroll) = autoscroll {
3272 self.request_autoscroll(autoscroll, cx);
3273 }
3274 self.pause_cursor_blinking(cx);
3275
3276 self.set_selections(
3277 Arc::from_iter(selections.into_iter().map(|selection| {
3278 let end_bias = if selection.end > selection.start {
3279 Bias::Left
3280 } else {
3281 Bias::Right
3282 };
3283 Selection {
3284 id: selection.id,
3285 start: buffer.anchor_after(selection.start),
3286 end: buffer.anchor_at(selection.end, end_bias),
3287 reversed: selection.reversed,
3288 goal: selection.goal,
3289 }
3290 })),
3291 cx,
3292 );
3293 }
3294
3295 fn set_selections(&mut self, selections: Arc<[Selection<Anchor>]>, cx: &mut ViewContext<Self>) {
3296 self.selections = selections;
3297 self.buffer.update(cx, |buffer, cx| {
3298 buffer.set_active_selections(&self.selections, cx)
3299 });
3300 }
3301
3302 fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3303 self.autoscroll_request = Some(autoscroll);
3304 cx.notify();
3305 }
3306
3307 fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3308 self.start_transaction_at(Instant::now(), cx);
3309 }
3310
3311 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3312 self.end_selection(cx);
3313 if let Some(tx_id) = self
3314 .buffer
3315 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
3316 {
3317 self.selection_history
3318 .insert(tx_id, (self.selections.clone(), None));
3319 }
3320 }
3321
3322 fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
3323 self.end_transaction_at(Instant::now(), cx);
3324 }
3325
3326 fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
3327 if let Some(tx_id) = self
3328 .buffer
3329 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
3330 {
3331 self.selection_history.get_mut(&tx_id).unwrap().1 = Some(self.selections.clone());
3332 }
3333 }
3334
3335 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3336 log::info!("Editor::page_up");
3337 }
3338
3339 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3340 log::info!("Editor::page_down");
3341 }
3342
3343 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3344 let mut fold_ranges = Vec::new();
3345
3346 let selections = self.local_selections::<Point>(cx);
3347 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3348 for selection in selections {
3349 let range = selection.display_range(&display_map).sorted();
3350 let buffer_start_row = range.start.to_point(&display_map).row;
3351
3352 for row in (0..=range.end.row()).rev() {
3353 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3354 let fold_range = self.foldable_range_for_line(&display_map, row);
3355 if fold_range.end.row >= buffer_start_row {
3356 fold_ranges.push(fold_range);
3357 if row <= range.start.row() {
3358 break;
3359 }
3360 }
3361 }
3362 }
3363 }
3364
3365 self.fold_ranges(fold_ranges, cx);
3366 }
3367
3368 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3369 let selections = self.local_selections::<Point>(cx);
3370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3371 let buffer = &display_map.buffer_snapshot;
3372 let ranges = selections
3373 .iter()
3374 .map(|s| {
3375 let range = s.display_range(&display_map).sorted();
3376 let mut start = range.start.to_point(&display_map);
3377 let mut end = range.end.to_point(&display_map);
3378 start.column = 0;
3379 end.column = buffer.line_len(end.row);
3380 start..end
3381 })
3382 .collect::<Vec<_>>();
3383 self.unfold_ranges(ranges, cx);
3384 }
3385
3386 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
3387 let max_point = display_map.max_point();
3388 if display_row >= max_point.row() {
3389 false
3390 } else {
3391 let (start_indent, is_blank) = display_map.line_indent(display_row);
3392 if is_blank {
3393 false
3394 } else {
3395 for display_row in display_row + 1..=max_point.row() {
3396 let (indent, is_blank) = display_map.line_indent(display_row);
3397 if !is_blank {
3398 return indent > start_indent;
3399 }
3400 }
3401 false
3402 }
3403 }
3404 }
3405
3406 fn foldable_range_for_line(
3407 &self,
3408 display_map: &DisplaySnapshot,
3409 start_row: u32,
3410 ) -> Range<Point> {
3411 let max_point = display_map.max_point();
3412
3413 let (start_indent, _) = display_map.line_indent(start_row);
3414 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3415 let mut end = None;
3416 for row in start_row + 1..=max_point.row() {
3417 let (indent, is_blank) = display_map.line_indent(row);
3418 if !is_blank && indent <= start_indent {
3419 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3420 break;
3421 }
3422 }
3423
3424 let end = end.unwrap_or(max_point);
3425 return start.to_point(display_map)..end.to_point(display_map);
3426 }
3427
3428 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3429 let selections = self.local_selections::<Point>(cx);
3430 let ranges = selections.into_iter().map(|s| s.start..s.end);
3431 self.fold_ranges(ranges, cx);
3432 }
3433
3434 fn fold_ranges<T: ToOffset>(
3435 &mut self,
3436 ranges: impl IntoIterator<Item = Range<T>>,
3437 cx: &mut ViewContext<Self>,
3438 ) {
3439 let mut ranges = ranges.into_iter().peekable();
3440 if ranges.peek().is_some() {
3441 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3442 self.request_autoscroll(Autoscroll::Fit, cx);
3443 cx.notify();
3444 }
3445 }
3446
3447 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3448 if !ranges.is_empty() {
3449 self.display_map
3450 .update(cx, |map, cx| map.unfold(ranges, cx));
3451 self.request_autoscroll(Autoscroll::Fit, cx);
3452 cx.notify();
3453 }
3454 }
3455
3456 pub fn insert_blocks<P>(
3457 &mut self,
3458 blocks: impl IntoIterator<Item = BlockProperties<P>>,
3459 cx: &mut ViewContext<Self>,
3460 ) -> Vec<BlockId>
3461 where
3462 P: ToOffset + Clone,
3463 {
3464 let blocks = self
3465 .display_map
3466 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
3467 self.request_autoscroll(Autoscroll::Fit, cx);
3468 blocks
3469 }
3470
3471 pub fn replace_blocks(
3472 &mut self,
3473 blocks: HashMap<BlockId, RenderBlock>,
3474 cx: &mut ViewContext<Self>,
3475 ) {
3476 self.display_map
3477 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
3478 self.request_autoscroll(Autoscroll::Fit, cx);
3479 }
3480
3481 pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
3482 self.display_map.update(cx, |display_map, cx| {
3483 display_map.remove_blocks(block_ids, cx)
3484 });
3485 }
3486
3487 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3488 self.display_map
3489 .update(cx, |map, cx| map.snapshot(cx))
3490 .longest_row()
3491 }
3492
3493 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3494 self.display_map
3495 .update(cx, |map, cx| map.snapshot(cx))
3496 .max_point()
3497 }
3498
3499 pub fn text(&self, cx: &AppContext) -> String {
3500 self.buffer.read(cx).read(cx).text()
3501 }
3502
3503 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3504 self.display_map
3505 .update(cx, |map, cx| map.snapshot(cx))
3506 .text()
3507 }
3508
3509 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
3510 self.display_map
3511 .update(cx, |map, cx| map.set_wrap_width(width, cx))
3512 }
3513
3514 pub fn set_highlighted_row(&mut self, row: Option<u32>) {
3515 self.highlighted_row = row;
3516 }
3517
3518 pub fn highlighted_row(&mut self) -> Option<u32> {
3519 self.highlighted_row
3520 }
3521
3522 fn next_blink_epoch(&mut self) -> usize {
3523 self.blink_epoch += 1;
3524 self.blink_epoch
3525 }
3526
3527 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3528 self.show_local_cursors = true;
3529 cx.notify();
3530
3531 let epoch = self.next_blink_epoch();
3532 cx.spawn(|this, mut cx| {
3533 let this = this.downgrade();
3534 async move {
3535 Timer::after(CURSOR_BLINK_INTERVAL).await;
3536 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3537 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3538 }
3539 }
3540 })
3541 .detach();
3542 }
3543
3544 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3545 if epoch == self.blink_epoch {
3546 self.blinking_paused = false;
3547 self.blink_cursors(epoch, cx);
3548 }
3549 }
3550
3551 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3552 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3553 self.show_local_cursors = !self.show_local_cursors;
3554 cx.notify();
3555
3556 let epoch = self.next_blink_epoch();
3557 cx.spawn(|this, mut cx| {
3558 let this = this.downgrade();
3559 async move {
3560 Timer::after(CURSOR_BLINK_INTERVAL).await;
3561 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3562 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3563 }
3564 }
3565 })
3566 .detach();
3567 }
3568 }
3569
3570 pub fn show_local_cursors(&self) -> bool {
3571 self.show_local_cursors
3572 }
3573
3574 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
3575 self.refresh_active_diagnostics(cx);
3576 cx.notify();
3577 }
3578
3579 fn on_buffer_event(
3580 &mut self,
3581 _: ModelHandle<MultiBuffer>,
3582 event: &language::Event,
3583 cx: &mut ViewContext<Self>,
3584 ) {
3585 match event {
3586 language::Event::Edited => cx.emit(Event::Edited),
3587 language::Event::Dirtied => cx.emit(Event::Dirtied),
3588 language::Event::Saved => cx.emit(Event::Saved),
3589 language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
3590 language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
3591 language::Event::Closed => cx.emit(Event::Closed),
3592 _ => {}
3593 }
3594 }
3595
3596 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3597 cx.notify();
3598 }
3599}
3600
3601impl EditorSnapshot {
3602 pub fn is_focused(&self) -> bool {
3603 self.is_focused
3604 }
3605
3606 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3607 self.placeholder_text.as_ref()
3608 }
3609
3610 pub fn scroll_position(&self) -> Vector2F {
3611 compute_scroll_position(
3612 &self.display_snapshot,
3613 self.scroll_position,
3614 &self.scroll_top_anchor,
3615 )
3616 }
3617}
3618
3619impl Deref for EditorSnapshot {
3620 type Target = DisplaySnapshot;
3621
3622 fn deref(&self) -> &Self::Target {
3623 &self.display_snapshot
3624 }
3625}
3626
3627impl EditorSettings {
3628 #[cfg(any(test, feature = "test-support"))]
3629 pub fn test(cx: &AppContext) -> Self {
3630 Self {
3631 tab_size: 4,
3632 soft_wrap: SoftWrap::None,
3633 style: {
3634 let font_cache: &gpui::FontCache = cx.font_cache();
3635 let font_family_name = Arc::from("Monaco");
3636 let font_properties = Default::default();
3637 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3638 let font_id = font_cache
3639 .select_font(font_family_id, &font_properties)
3640 .unwrap();
3641 EditorStyle {
3642 text: gpui::fonts::TextStyle {
3643 font_family_name,
3644 font_family_id,
3645 font_id,
3646 font_size: 14.,
3647 color: gpui::color::Color::from_u32(0xff0000ff),
3648 font_properties,
3649 underline: None,
3650 },
3651 placeholder_text: None,
3652 background: Default::default(),
3653 gutter_background: Default::default(),
3654 active_line_background: Default::default(),
3655 highlighted_line_background: Default::default(),
3656 line_number: Default::default(),
3657 line_number_active: Default::default(),
3658 selection: Default::default(),
3659 guest_selections: Default::default(),
3660 syntax: Default::default(),
3661 error_diagnostic: Default::default(),
3662 invalid_error_diagnostic: Default::default(),
3663 warning_diagnostic: Default::default(),
3664 invalid_warning_diagnostic: Default::default(),
3665 information_diagnostic: Default::default(),
3666 invalid_information_diagnostic: Default::default(),
3667 hint_diagnostic: Default::default(),
3668 invalid_hint_diagnostic: Default::default(),
3669 }
3670 },
3671 }
3672 }
3673}
3674
3675fn compute_scroll_position(
3676 snapshot: &DisplaySnapshot,
3677 mut scroll_position: Vector2F,
3678 scroll_top_anchor: &Anchor,
3679) -> Vector2F {
3680 let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3681 scroll_position.set_y(scroll_top + scroll_position.y());
3682 scroll_position
3683}
3684
3685#[derive(Copy, Clone)]
3686pub enum Event {
3687 Activate,
3688 Edited,
3689 Blurred,
3690 Dirtied,
3691 Saved,
3692 FileHandleChanged,
3693 Closed,
3694}
3695
3696impl Entity for Editor {
3697 type Event = Event;
3698}
3699
3700impl View for Editor {
3701 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3702 let settings = (self.build_settings)(cx);
3703 self.display_map.update(cx, |map, cx| {
3704 map.set_font(
3705 settings.style.text.font_id,
3706 settings.style.text.font_size,
3707 cx,
3708 )
3709 });
3710 EditorElement::new(self.handle.clone(), settings).boxed()
3711 }
3712
3713 fn ui_name() -> &'static str {
3714 "Editor"
3715 }
3716
3717 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3718 self.focused = true;
3719 self.blink_cursors(self.blink_epoch, cx);
3720 self.buffer.update(cx, |buffer, cx| {
3721 buffer.set_active_selections(&self.selections, cx)
3722 });
3723 }
3724
3725 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3726 self.focused = false;
3727 self.show_local_cursors = false;
3728 self.buffer
3729 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
3730 cx.emit(Event::Blurred);
3731 cx.notify();
3732 }
3733
3734 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3735 let mut cx = Self::default_keymap_context();
3736 let mode = match self.mode {
3737 EditorMode::SingleLine => "single_line",
3738 EditorMode::AutoHeight { .. } => "auto_height",
3739 EditorMode::Full => "full",
3740 };
3741 cx.map.insert("mode".into(), mode.into());
3742 cx
3743 }
3744}
3745
3746impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3747 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3748 let start = self.start.to_point(buffer);
3749 let end = self.end.to_point(buffer);
3750 if self.reversed {
3751 end..start
3752 } else {
3753 start..end
3754 }
3755 }
3756
3757 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3758 let start = self.start.to_offset(buffer);
3759 let end = self.end.to_offset(buffer);
3760 if self.reversed {
3761 end..start
3762 } else {
3763 start..end
3764 }
3765 }
3766
3767 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
3768 let start = self
3769 .start
3770 .to_point(&map.buffer_snapshot)
3771 .to_display_point(map);
3772 let end = self
3773 .end
3774 .to_point(&map.buffer_snapshot)
3775 .to_display_point(map);
3776 if self.reversed {
3777 end..start
3778 } else {
3779 start..end
3780 }
3781 }
3782
3783 fn spanned_rows(
3784 &self,
3785 include_end_if_at_line_start: bool,
3786 map: &DisplaySnapshot,
3787 ) -> SpannedRows {
3788 let display_start = self
3789 .start
3790 .to_point(&map.buffer_snapshot)
3791 .to_display_point(map);
3792 let mut display_end = self
3793 .end
3794 .to_point(&map.buffer_snapshot)
3795 .to_display_point(map);
3796 if !include_end_if_at_line_start
3797 && display_end.row() != map.max_point().row()
3798 && display_start.row() != display_end.row()
3799 && display_end.column() == 0
3800 {
3801 *display_end.row_mut() -= 1;
3802 }
3803
3804 let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3805 let (display_end, buffer_end) = map.next_row_boundary(display_end);
3806
3807 SpannedRows {
3808 buffer_rows: buffer_start.row..buffer_end.row + 1,
3809 display_rows: display_start.row()..display_end.row() + 1,
3810 }
3811 }
3812}
3813
3814pub fn diagnostic_block_renderer(
3815 diagnostic: Diagnostic,
3816 is_valid: bool,
3817 build_settings: BuildSettings,
3818) -> RenderBlock {
3819 Arc::new(move |cx: &BlockContext| {
3820 let settings = build_settings(cx);
3821 let mut text_style = settings.style.text.clone();
3822 text_style.color = diagnostic_style(diagnostic.severity, is_valid, &settings.style).text;
3823 Text::new(diagnostic.message.clone(), text_style)
3824 .contained()
3825 .with_margin_left(cx.anchor_x)
3826 .boxed()
3827 })
3828}
3829
3830pub fn diagnostic_header_renderer(
3831 buffer: ModelHandle<Buffer>,
3832 diagnostic: Diagnostic,
3833 is_valid: bool,
3834 build_settings: BuildSettings,
3835) -> RenderBlock {
3836 Arc::new(move |cx| {
3837 let settings = build_settings(cx);
3838 let mut text_style = settings.style.text.clone();
3839 text_style.color = diagnostic_style(diagnostic.severity, is_valid, &settings.style).text;
3840 let file_path = if let Some(file) = buffer.read(&**cx).file() {
3841 file.path().to_string_lossy().to_string()
3842 } else {
3843 "untitled".to_string()
3844 };
3845
3846 Flex::column()
3847 .with_child(Label::new(diagnostic.message.clone(), text_style).boxed())
3848 .with_child(Label::new(file_path, settings.style.text.clone()).boxed())
3849 .boxed()
3850 })
3851}
3852
3853pub fn context_header_renderer(build_settings: BuildSettings) -> RenderBlock {
3854 Arc::new(move |cx| {
3855 let settings = build_settings(cx);
3856 let text_style = settings.style.text.clone();
3857 Label::new("...".to_string(), text_style).boxed()
3858 })
3859}
3860
3861pub fn diagnostic_style(
3862 severity: DiagnosticSeverity,
3863 valid: bool,
3864 style: &EditorStyle,
3865) -> DiagnosticStyle {
3866 match (severity, valid) {
3867 (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3868 (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3869 (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3870 (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3871 (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3872 (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3873 (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3874 (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3875 _ => Default::default(),
3876 }
3877}
3878
3879pub fn settings_builder(
3880 buffer: WeakModelHandle<MultiBuffer>,
3881 settings: watch::Receiver<workspace::Settings>,
3882) -> BuildSettings {
3883 Arc::new(move |cx| {
3884 let settings = settings.borrow();
3885 let font_cache = cx.font_cache();
3886 let font_family_id = settings.buffer_font_family;
3887 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
3888 let font_properties = Default::default();
3889 let font_id = font_cache
3890 .select_font(font_family_id, &font_properties)
3891 .unwrap();
3892 let font_size = settings.buffer_font_size;
3893
3894 let mut theme = settings.theme.editor.clone();
3895 theme.text = TextStyle {
3896 color: theme.text.color,
3897 font_family_name,
3898 font_family_id,
3899 font_id,
3900 font_size,
3901 font_properties,
3902 underline: None,
3903 };
3904 let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
3905 let soft_wrap = match settings.soft_wrap(language) {
3906 workspace::settings::SoftWrap::None => SoftWrap::None,
3907 workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
3908 workspace::settings::SoftWrap::PreferredLineLength => {
3909 SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
3910 }
3911 };
3912
3913 EditorSettings {
3914 tab_size: settings.tab_size,
3915 soft_wrap,
3916 style: theme,
3917 }
3918 })
3919}
3920
3921#[cfg(test)]
3922mod tests {
3923 use super::*;
3924 use language::LanguageConfig;
3925 use std::time::Instant;
3926 use text::Point;
3927 use unindent::Unindent;
3928 use util::test::sample_text;
3929
3930 #[gpui::test]
3931 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
3932 let mut now = Instant::now();
3933 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
3934 let group_interval = buffer.read(cx).transaction_group_interval();
3935 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
3936 let settings = EditorSettings::test(cx);
3937 let (_, editor) = cx.add_window(Default::default(), |cx| {
3938 build_editor(buffer.clone(), settings, cx)
3939 });
3940
3941 editor.update(cx, |editor, cx| {
3942 editor.start_transaction_at(now, cx);
3943 editor.select_ranges([2..4], None, cx);
3944 editor.insert("cd", cx);
3945 editor.end_transaction_at(now, cx);
3946 assert_eq!(editor.text(cx), "12cd56");
3947 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
3948
3949 editor.start_transaction_at(now, cx);
3950 editor.select_ranges([4..5], None, cx);
3951 editor.insert("e", cx);
3952 editor.end_transaction_at(now, cx);
3953 assert_eq!(editor.text(cx), "12cde6");
3954 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3955
3956 now += group_interval + Duration::from_millis(1);
3957 editor.select_ranges([2..2], None, cx);
3958
3959 // Simulate an edit in another editor
3960 buffer.update(cx, |buffer, cx| {
3961 buffer.start_transaction_at(now, cx);
3962 buffer.edit([0..1], "a", cx);
3963 buffer.edit([1..1], "b", cx);
3964 buffer.end_transaction_at(now, cx);
3965 });
3966
3967 assert_eq!(editor.text(cx), "ab2cde6");
3968 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
3969
3970 // Last transaction happened past the group interval in a different editor.
3971 // Undo it individually and don't restore selections.
3972 editor.undo(&Undo, cx);
3973 assert_eq!(editor.text(cx), "12cde6");
3974 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
3975
3976 // First two transactions happened within the group interval in this editor.
3977 // Undo them together and restore selections.
3978 editor.undo(&Undo, cx);
3979 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
3980 assert_eq!(editor.text(cx), "123456");
3981 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
3982
3983 // Redo the first two transactions together.
3984 editor.redo(&Redo, cx);
3985 assert_eq!(editor.text(cx), "12cde6");
3986 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
3987
3988 // Redo the last transaction on its own.
3989 editor.redo(&Redo, cx);
3990 assert_eq!(editor.text(cx), "ab2cde6");
3991 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
3992
3993 // Test empty transactions.
3994 editor.start_transaction_at(now, cx);
3995 editor.end_transaction_at(now, cx);
3996 editor.undo(&Undo, cx);
3997 assert_eq!(editor.text(cx), "12cde6");
3998 });
3999 }
4000
4001 #[gpui::test]
4002 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
4003 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4004 let settings = EditorSettings::test(cx);
4005 let (_, editor) =
4006 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4007
4008 editor.update(cx, |view, cx| {
4009 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4010 });
4011
4012 assert_eq!(
4013 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4014 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4015 );
4016
4017 editor.update(cx, |view, cx| {
4018 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4019 });
4020
4021 assert_eq!(
4022 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4023 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4024 );
4025
4026 editor.update(cx, |view, cx| {
4027 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4028 });
4029
4030 assert_eq!(
4031 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4032 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4033 );
4034
4035 editor.update(cx, |view, cx| {
4036 view.end_selection(cx);
4037 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4038 });
4039
4040 assert_eq!(
4041 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4042 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4043 );
4044
4045 editor.update(cx, |view, cx| {
4046 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
4047 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
4048 });
4049
4050 assert_eq!(
4051 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4052 [
4053 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
4054 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
4055 ]
4056 );
4057
4058 editor.update(cx, |view, cx| {
4059 view.end_selection(cx);
4060 });
4061
4062 assert_eq!(
4063 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4064 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
4065 );
4066 }
4067
4068 #[gpui::test]
4069 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
4070 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4071 let settings = EditorSettings::test(cx);
4072 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4073
4074 view.update(cx, |view, cx| {
4075 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4076 assert_eq!(
4077 view.selected_display_ranges(cx),
4078 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4079 );
4080 });
4081
4082 view.update(cx, |view, cx| {
4083 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4084 assert_eq!(
4085 view.selected_display_ranges(cx),
4086 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4087 );
4088 });
4089
4090 view.update(cx, |view, cx| {
4091 view.cancel(&Cancel, cx);
4092 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4093 assert_eq!(
4094 view.selected_display_ranges(cx),
4095 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4096 );
4097 });
4098 }
4099
4100 #[gpui::test]
4101 fn test_cancel(cx: &mut gpui::MutableAppContext) {
4102 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4103 let settings = EditorSettings::test(cx);
4104 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4105
4106 view.update(cx, |view, cx| {
4107 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
4108 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4109 view.end_selection(cx);
4110
4111 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
4112 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
4113 view.end_selection(cx);
4114 assert_eq!(
4115 view.selected_display_ranges(cx),
4116 [
4117 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4118 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
4119 ]
4120 );
4121 });
4122
4123 view.update(cx, |view, cx| {
4124 view.cancel(&Cancel, cx);
4125 assert_eq!(
4126 view.selected_display_ranges(cx),
4127 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
4128 );
4129 });
4130
4131 view.update(cx, |view, cx| {
4132 view.cancel(&Cancel, cx);
4133 assert_eq!(
4134 view.selected_display_ranges(cx),
4135 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4136 );
4137 });
4138 }
4139
4140 #[gpui::test]
4141 fn test_fold(cx: &mut gpui::MutableAppContext) {
4142 let buffer = MultiBuffer::build_simple(
4143 &"
4144 impl Foo {
4145 // Hello!
4146
4147 fn a() {
4148 1
4149 }
4150
4151 fn b() {
4152 2
4153 }
4154
4155 fn c() {
4156 3
4157 }
4158 }
4159 "
4160 .unindent(),
4161 cx,
4162 );
4163 let settings = EditorSettings::test(&cx);
4164 let (_, view) = cx.add_window(Default::default(), |cx| {
4165 build_editor(buffer.clone(), settings, cx)
4166 });
4167
4168 view.update(cx, |view, cx| {
4169 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
4170 .unwrap();
4171 view.fold(&Fold, cx);
4172 assert_eq!(
4173 view.display_text(cx),
4174 "
4175 impl Foo {
4176 // Hello!
4177
4178 fn a() {
4179 1
4180 }
4181
4182 fn b() {…
4183 }
4184
4185 fn c() {…
4186 }
4187 }
4188 "
4189 .unindent(),
4190 );
4191
4192 view.fold(&Fold, cx);
4193 assert_eq!(
4194 view.display_text(cx),
4195 "
4196 impl Foo {…
4197 }
4198 "
4199 .unindent(),
4200 );
4201
4202 view.unfold(&Unfold, cx);
4203 assert_eq!(
4204 view.display_text(cx),
4205 "
4206 impl Foo {
4207 // Hello!
4208
4209 fn a() {
4210 1
4211 }
4212
4213 fn b() {…
4214 }
4215
4216 fn c() {…
4217 }
4218 }
4219 "
4220 .unindent(),
4221 );
4222
4223 view.unfold(&Unfold, cx);
4224 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4225 });
4226 }
4227
4228 #[gpui::test]
4229 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4230 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4231 let settings = EditorSettings::test(&cx);
4232 let (_, view) = cx.add_window(Default::default(), |cx| {
4233 build_editor(buffer.clone(), settings, cx)
4234 });
4235
4236 buffer.update(cx, |buffer, cx| {
4237 buffer.edit(
4238 vec![
4239 Point::new(1, 0)..Point::new(1, 0),
4240 Point::new(1, 1)..Point::new(1, 1),
4241 ],
4242 "\t",
4243 cx,
4244 );
4245 });
4246
4247 view.update(cx, |view, cx| {
4248 assert_eq!(
4249 view.selected_display_ranges(cx),
4250 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4251 );
4252
4253 view.move_down(&MoveDown, cx);
4254 assert_eq!(
4255 view.selected_display_ranges(cx),
4256 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4257 );
4258
4259 view.move_right(&MoveRight, cx);
4260 assert_eq!(
4261 view.selected_display_ranges(cx),
4262 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4263 );
4264
4265 view.move_left(&MoveLeft, cx);
4266 assert_eq!(
4267 view.selected_display_ranges(cx),
4268 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4269 );
4270
4271 view.move_up(&MoveUp, cx);
4272 assert_eq!(
4273 view.selected_display_ranges(cx),
4274 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4275 );
4276
4277 view.move_to_end(&MoveToEnd, cx);
4278 assert_eq!(
4279 view.selected_display_ranges(cx),
4280 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4281 );
4282
4283 view.move_to_beginning(&MoveToBeginning, cx);
4284 assert_eq!(
4285 view.selected_display_ranges(cx),
4286 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4287 );
4288
4289 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4290 .unwrap();
4291 view.select_to_beginning(&SelectToBeginning, cx);
4292 assert_eq!(
4293 view.selected_display_ranges(cx),
4294 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4295 );
4296
4297 view.select_to_end(&SelectToEnd, cx);
4298 assert_eq!(
4299 view.selected_display_ranges(cx),
4300 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4301 );
4302 });
4303 }
4304
4305 #[gpui::test]
4306 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4307 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4308 let settings = EditorSettings::test(&cx);
4309 let (_, view) = cx.add_window(Default::default(), |cx| {
4310 build_editor(buffer.clone(), settings, cx)
4311 });
4312
4313 assert_eq!('ⓐ'.len_utf8(), 3);
4314 assert_eq!('α'.len_utf8(), 2);
4315
4316 view.update(cx, |view, cx| {
4317 view.fold_ranges(
4318 vec![
4319 Point::new(0, 6)..Point::new(0, 12),
4320 Point::new(1, 2)..Point::new(1, 4),
4321 Point::new(2, 4)..Point::new(2, 8),
4322 ],
4323 cx,
4324 );
4325 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
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 view.move_right(&MoveRight, cx);
4338 assert_eq!(
4339 view.selected_display_ranges(cx),
4340 &[empty_range(0, "ⓐⓑ…".len())]
4341 );
4342
4343 view.move_down(&MoveDown, 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, "ab".len())]
4352 );
4353 view.move_left(&MoveLeft, cx);
4354 assert_eq!(
4355 view.selected_display_ranges(cx),
4356 &[empty_range(1, "a".len())]
4357 );
4358
4359 view.move_down(&MoveDown, 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 view.move_right(&MoveRight, cx);
4375 assert_eq!(
4376 view.selected_display_ranges(cx),
4377 &[empty_range(2, "αβ…ε".len())]
4378 );
4379
4380 view.move_up(&MoveUp, cx);
4381 assert_eq!(
4382 view.selected_display_ranges(cx),
4383 &[empty_range(1, "ab…e".len())]
4384 );
4385 view.move_up(&MoveUp, 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 view.move_left(&MoveLeft, cx);
4401 assert_eq!(
4402 view.selected_display_ranges(cx),
4403 &[empty_range(0, "ⓐ".len())]
4404 );
4405 });
4406 }
4407
4408 #[gpui::test]
4409 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4410 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4411 let settings = EditorSettings::test(&cx);
4412 let (_, view) = cx.add_window(Default::default(), |cx| {
4413 build_editor(buffer.clone(), settings, cx)
4414 });
4415 view.update(cx, |view, cx| {
4416 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4417 .unwrap();
4418
4419 view.move_down(&MoveDown, cx);
4420 assert_eq!(
4421 view.selected_display_ranges(cx),
4422 &[empty_range(1, "abcd".len())]
4423 );
4424
4425 view.move_down(&MoveDown, cx);
4426 assert_eq!(
4427 view.selected_display_ranges(cx),
4428 &[empty_range(2, "αβγ".len())]
4429 );
4430
4431 view.move_down(&MoveDown, cx);
4432 assert_eq!(
4433 view.selected_display_ranges(cx),
4434 &[empty_range(3, "abcd".len())]
4435 );
4436
4437 view.move_down(&MoveDown, cx);
4438 assert_eq!(
4439 view.selected_display_ranges(cx),
4440 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4441 );
4442
4443 view.move_up(&MoveUp, cx);
4444 assert_eq!(
4445 view.selected_display_ranges(cx),
4446 &[empty_range(3, "abcd".len())]
4447 );
4448
4449 view.move_up(&MoveUp, cx);
4450 assert_eq!(
4451 view.selected_display_ranges(cx),
4452 &[empty_range(2, "αβγ".len())]
4453 );
4454 });
4455 }
4456
4457 #[gpui::test]
4458 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4459 let buffer = MultiBuffer::build_simple("abc\n def", cx);
4460 let settings = EditorSettings::test(&cx);
4461 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4462 view.update(cx, |view, cx| {
4463 view.select_display_ranges(
4464 &[
4465 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4466 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4467 ],
4468 cx,
4469 )
4470 .unwrap();
4471 });
4472
4473 view.update(cx, |view, cx| {
4474 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4475 assert_eq!(
4476 view.selected_display_ranges(cx),
4477 &[
4478 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4479 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4480 ]
4481 );
4482 });
4483
4484 view.update(cx, |view, cx| {
4485 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4486 assert_eq!(
4487 view.selected_display_ranges(cx),
4488 &[
4489 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4490 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4491 ]
4492 );
4493 });
4494
4495 view.update(cx, |view, cx| {
4496 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4497 assert_eq!(
4498 view.selected_display_ranges(cx),
4499 &[
4500 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4501 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4502 ]
4503 );
4504 });
4505
4506 view.update(cx, |view, cx| {
4507 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4508 assert_eq!(
4509 view.selected_display_ranges(cx),
4510 &[
4511 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4512 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4513 ]
4514 );
4515 });
4516
4517 // Moving to the end of line again is a no-op.
4518 view.update(cx, |view, cx| {
4519 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4520 assert_eq!(
4521 view.selected_display_ranges(cx),
4522 &[
4523 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4524 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4525 ]
4526 );
4527 });
4528
4529 view.update(cx, |view, cx| {
4530 view.move_left(&MoveLeft, cx);
4531 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4532 assert_eq!(
4533 view.selected_display_ranges(cx),
4534 &[
4535 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4536 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4537 ]
4538 );
4539 });
4540
4541 view.update(cx, |view, cx| {
4542 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4543 assert_eq!(
4544 view.selected_display_ranges(cx),
4545 &[
4546 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4547 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4548 ]
4549 );
4550 });
4551
4552 view.update(cx, |view, cx| {
4553 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4554 assert_eq!(
4555 view.selected_display_ranges(cx),
4556 &[
4557 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4558 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4559 ]
4560 );
4561 });
4562
4563 view.update(cx, |view, cx| {
4564 view.select_to_end_of_line(&SelectToEndOfLine, cx);
4565 assert_eq!(
4566 view.selected_display_ranges(cx),
4567 &[
4568 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4569 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4570 ]
4571 );
4572 });
4573
4574 view.update(cx, |view, cx| {
4575 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4576 assert_eq!(view.display_text(cx), "ab\n de");
4577 assert_eq!(
4578 view.selected_display_ranges(cx),
4579 &[
4580 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4581 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4582 ]
4583 );
4584 });
4585
4586 view.update(cx, |view, cx| {
4587 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4588 assert_eq!(view.display_text(cx), "\n");
4589 assert_eq!(
4590 view.selected_display_ranges(cx),
4591 &[
4592 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4593 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4594 ]
4595 );
4596 });
4597 }
4598
4599 #[gpui::test]
4600 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4601 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
4602 let settings = EditorSettings::test(&cx);
4603 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4604 view.update(cx, |view, cx| {
4605 view.select_display_ranges(
4606 &[
4607 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4608 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4609 ],
4610 cx,
4611 )
4612 .unwrap();
4613 });
4614
4615 view.update(cx, |view, cx| {
4616 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4617 assert_eq!(
4618 view.selected_display_ranges(cx),
4619 &[
4620 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4621 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4622 ]
4623 );
4624 });
4625
4626 view.update(cx, |view, cx| {
4627 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4628 assert_eq!(
4629 view.selected_display_ranges(cx),
4630 &[
4631 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4632 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4633 ]
4634 );
4635 });
4636
4637 view.update(cx, |view, cx| {
4638 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4639 assert_eq!(
4640 view.selected_display_ranges(cx),
4641 &[
4642 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4643 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4644 ]
4645 );
4646 });
4647
4648 view.update(cx, |view, cx| {
4649 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4650 assert_eq!(
4651 view.selected_display_ranges(cx),
4652 &[
4653 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4654 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4655 ]
4656 );
4657 });
4658
4659 view.update(cx, |view, cx| {
4660 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4661 assert_eq!(
4662 view.selected_display_ranges(cx),
4663 &[
4664 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4665 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4666 ]
4667 );
4668 });
4669
4670 view.update(cx, |view, cx| {
4671 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4672 assert_eq!(
4673 view.selected_display_ranges(cx),
4674 &[
4675 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4676 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4677 ]
4678 );
4679 });
4680
4681 view.update(cx, |view, cx| {
4682 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4683 assert_eq!(
4684 view.selected_display_ranges(cx),
4685 &[
4686 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4687 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4688 ]
4689 );
4690 });
4691
4692 view.update(cx, |view, cx| {
4693 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4694 assert_eq!(
4695 view.selected_display_ranges(cx),
4696 &[
4697 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4698 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4699 ]
4700 );
4701 });
4702
4703 view.update(cx, |view, cx| {
4704 view.move_right(&MoveRight, cx);
4705 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4706 assert_eq!(
4707 view.selected_display_ranges(cx),
4708 &[
4709 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4710 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4711 ]
4712 );
4713 });
4714
4715 view.update(cx, |view, cx| {
4716 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4717 assert_eq!(
4718 view.selected_display_ranges(cx),
4719 &[
4720 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4721 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4722 ]
4723 );
4724 });
4725
4726 view.update(cx, |view, cx| {
4727 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4728 assert_eq!(
4729 view.selected_display_ranges(cx),
4730 &[
4731 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4732 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4733 ]
4734 );
4735 });
4736 }
4737
4738 #[gpui::test]
4739 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4740 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
4741 let settings = EditorSettings::test(&cx);
4742 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4743
4744 view.update(cx, |view, cx| {
4745 view.set_wrap_width(Some(140.), cx);
4746 assert_eq!(
4747 view.display_text(cx),
4748 "use one::{\n two::three::\n four::five\n};"
4749 );
4750
4751 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4752 .unwrap();
4753
4754 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4755 assert_eq!(
4756 view.selected_display_ranges(cx),
4757 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4758 );
4759
4760 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4761 assert_eq!(
4762 view.selected_display_ranges(cx),
4763 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4764 );
4765
4766 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4767 assert_eq!(
4768 view.selected_display_ranges(cx),
4769 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4770 );
4771
4772 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4773 assert_eq!(
4774 view.selected_display_ranges(cx),
4775 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4776 );
4777
4778 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4779 assert_eq!(
4780 view.selected_display_ranges(cx),
4781 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4782 );
4783
4784 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4785 assert_eq!(
4786 view.selected_display_ranges(cx),
4787 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4788 );
4789 });
4790 }
4791
4792 #[gpui::test]
4793 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4794 let buffer = MultiBuffer::build_simple("one two three four", cx);
4795 let settings = EditorSettings::test(&cx);
4796 let (_, view) = cx.add_window(Default::default(), |cx| {
4797 build_editor(buffer.clone(), settings, cx)
4798 });
4799
4800 view.update(cx, |view, cx| {
4801 view.select_display_ranges(
4802 &[
4803 // an empty selection - the preceding word fragment is deleted
4804 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4805 // characters selected - they are deleted
4806 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4807 ],
4808 cx,
4809 )
4810 .unwrap();
4811 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4812 });
4813
4814 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
4815
4816 view.update(cx, |view, cx| {
4817 view.select_display_ranges(
4818 &[
4819 // an empty selection - the following word fragment is deleted
4820 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4821 // characters selected - they are deleted
4822 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4823 ],
4824 cx,
4825 )
4826 .unwrap();
4827 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4828 });
4829
4830 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
4831 }
4832
4833 #[gpui::test]
4834 fn test_newline(cx: &mut gpui::MutableAppContext) {
4835 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
4836 let settings = EditorSettings::test(&cx);
4837 let (_, view) = cx.add_window(Default::default(), |cx| {
4838 build_editor(buffer.clone(), settings, cx)
4839 });
4840
4841 view.update(cx, |view, cx| {
4842 view.select_display_ranges(
4843 &[
4844 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4845 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4846 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4847 ],
4848 cx,
4849 )
4850 .unwrap();
4851
4852 view.newline(&Newline, cx);
4853 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
4854 });
4855 }
4856
4857 #[gpui::test]
4858 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4859 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
4860 let settings = EditorSettings::test(&cx);
4861 let (_, view) = cx.add_window(Default::default(), |cx| {
4862 build_editor(buffer.clone(), settings, cx)
4863 });
4864
4865 view.update(cx, |view, cx| {
4866 // two selections on the same line
4867 view.select_display_ranges(
4868 &[
4869 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4870 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4871 ],
4872 cx,
4873 )
4874 .unwrap();
4875
4876 // indent from mid-tabstop to full tabstop
4877 view.tab(&Tab, cx);
4878 assert_eq!(view.text(cx), " one two\nthree\n four");
4879 assert_eq!(
4880 view.selected_display_ranges(cx),
4881 &[
4882 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4883 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4884 ]
4885 );
4886
4887 // outdent from 1 tabstop to 0 tabstops
4888 view.outdent(&Outdent, cx);
4889 assert_eq!(view.text(cx), "one two\nthree\n four");
4890 assert_eq!(
4891 view.selected_display_ranges(cx),
4892 &[
4893 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4894 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4895 ]
4896 );
4897
4898 // select across line ending
4899 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4900 .unwrap();
4901
4902 // indent and outdent affect only the preceding line
4903 view.tab(&Tab, cx);
4904 assert_eq!(view.text(cx), "one two\n three\n four");
4905 assert_eq!(
4906 view.selected_display_ranges(cx),
4907 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4908 );
4909 view.outdent(&Outdent, cx);
4910 assert_eq!(view.text(cx), "one two\nthree\n four");
4911 assert_eq!(
4912 view.selected_display_ranges(cx),
4913 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4914 );
4915 });
4916 }
4917
4918 #[gpui::test]
4919 fn test_backspace(cx: &mut gpui::MutableAppContext) {
4920 let buffer =
4921 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4922 let settings = EditorSettings::test(&cx);
4923 let (_, view) = cx.add_window(Default::default(), |cx| {
4924 build_editor(buffer.clone(), settings, cx)
4925 });
4926
4927 view.update(cx, |view, cx| {
4928 view.select_display_ranges(
4929 &[
4930 // an empty selection - the preceding character is deleted
4931 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4932 // one character selected - it is deleted
4933 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4934 // a line suffix selected - it is deleted
4935 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4936 ],
4937 cx,
4938 )
4939 .unwrap();
4940 view.backspace(&Backspace, cx);
4941 });
4942
4943 assert_eq!(
4944 buffer.read(cx).read(cx).text(),
4945 "oe two three\nfou five six\nseven ten\n"
4946 );
4947 }
4948
4949 #[gpui::test]
4950 fn test_delete(cx: &mut gpui::MutableAppContext) {
4951 let buffer =
4952 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4953 let settings = EditorSettings::test(&cx);
4954 let (_, view) = cx.add_window(Default::default(), |cx| {
4955 build_editor(buffer.clone(), settings, cx)
4956 });
4957
4958 view.update(cx, |view, cx| {
4959 view.select_display_ranges(
4960 &[
4961 // an empty selection - the following character is deleted
4962 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4963 // one character selected - it is deleted
4964 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4965 // a line suffix selected - it is deleted
4966 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4967 ],
4968 cx,
4969 )
4970 .unwrap();
4971 view.delete(&Delete, cx);
4972 });
4973
4974 assert_eq!(
4975 buffer.read(cx).read(cx).text(),
4976 "on two three\nfou five six\nseven ten\n"
4977 );
4978 }
4979
4980 #[gpui::test]
4981 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4982 let settings = EditorSettings::test(&cx);
4983 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4984 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4985 view.update(cx, |view, cx| {
4986 view.select_display_ranges(
4987 &[
4988 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4989 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4990 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4991 ],
4992 cx,
4993 )
4994 .unwrap();
4995 view.delete_line(&DeleteLine, cx);
4996 assert_eq!(view.display_text(cx), "ghi");
4997 assert_eq!(
4998 view.selected_display_ranges(cx),
4999 vec![
5000 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5001 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
5002 ]
5003 );
5004 });
5005
5006 let settings = EditorSettings::test(&cx);
5007 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5008 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5009 view.update(cx, |view, cx| {
5010 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
5011 .unwrap();
5012 view.delete_line(&DeleteLine, cx);
5013 assert_eq!(view.display_text(cx), "ghi\n");
5014 assert_eq!(
5015 view.selected_display_ranges(cx),
5016 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
5017 );
5018 });
5019 }
5020
5021 #[gpui::test]
5022 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
5023 let settings = EditorSettings::test(&cx);
5024 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5025 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5026 view.update(cx, |view, cx| {
5027 view.select_display_ranges(
5028 &[
5029 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5030 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5031 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5032 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5033 ],
5034 cx,
5035 )
5036 .unwrap();
5037 view.duplicate_line(&DuplicateLine, cx);
5038 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
5039 assert_eq!(
5040 view.selected_display_ranges(cx),
5041 vec![
5042 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5043 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5044 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5045 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
5046 ]
5047 );
5048 });
5049
5050 let settings = EditorSettings::test(&cx);
5051 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5052 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5053 view.update(cx, |view, cx| {
5054 view.select_display_ranges(
5055 &[
5056 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
5057 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
5058 ],
5059 cx,
5060 )
5061 .unwrap();
5062 view.duplicate_line(&DuplicateLine, cx);
5063 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
5064 assert_eq!(
5065 view.selected_display_ranges(cx),
5066 vec![
5067 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
5068 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
5069 ]
5070 );
5071 });
5072 }
5073
5074 #[gpui::test]
5075 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
5076 let settings = EditorSettings::test(&cx);
5077 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5078 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5079 view.update(cx, |view, cx| {
5080 view.fold_ranges(
5081 vec![
5082 Point::new(0, 2)..Point::new(1, 2),
5083 Point::new(2, 3)..Point::new(4, 1),
5084 Point::new(7, 0)..Point::new(8, 4),
5085 ],
5086 cx,
5087 );
5088 view.select_display_ranges(
5089 &[
5090 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5091 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5092 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5093 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
5094 ],
5095 cx,
5096 )
5097 .unwrap();
5098 assert_eq!(
5099 view.display_text(cx),
5100 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
5101 );
5102
5103 view.move_line_up(&MoveLineUp, cx);
5104 assert_eq!(
5105 view.display_text(cx),
5106 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
5107 );
5108 assert_eq!(
5109 view.selected_display_ranges(cx),
5110 vec![
5111 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5112 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5113 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5114 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5115 ]
5116 );
5117 });
5118
5119 view.update(cx, |view, cx| {
5120 view.move_line_down(&MoveLineDown, cx);
5121 assert_eq!(
5122 view.display_text(cx),
5123 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
5124 );
5125 assert_eq!(
5126 view.selected_display_ranges(cx),
5127 vec![
5128 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5129 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5130 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5131 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5132 ]
5133 );
5134 });
5135
5136 view.update(cx, |view, cx| {
5137 view.move_line_down(&MoveLineDown, cx);
5138 assert_eq!(
5139 view.display_text(cx),
5140 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5141 );
5142 assert_eq!(
5143 view.selected_display_ranges(cx),
5144 vec![
5145 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5146 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5147 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5148 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5149 ]
5150 );
5151 });
5152
5153 view.update(cx, |view, cx| {
5154 view.move_line_up(&MoveLineUp, cx);
5155 assert_eq!(
5156 view.display_text(cx),
5157 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5158 );
5159 assert_eq!(
5160 view.selected_display_ranges(cx),
5161 vec![
5162 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5163 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5164 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5165 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5166 ]
5167 );
5168 });
5169 }
5170
5171 #[gpui::test]
5172 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5173 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5174 let settings = EditorSettings::test(&cx);
5175 let view = cx
5176 .add_window(Default::default(), |cx| {
5177 build_editor(buffer.clone(), settings, cx)
5178 })
5179 .1;
5180
5181 // Cut with three selections. Clipboard text is divided into three slices.
5182 view.update(cx, |view, cx| {
5183 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5184 view.cut(&Cut, cx);
5185 assert_eq!(view.display_text(cx), "two four six ");
5186 });
5187
5188 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5189 view.update(cx, |view, cx| {
5190 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5191 view.paste(&Paste, cx);
5192 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5193 assert_eq!(
5194 view.selected_display_ranges(cx),
5195 &[
5196 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5197 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5198 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5199 ]
5200 );
5201 });
5202
5203 // Paste again but with only two cursors. Since the number of cursors doesn't
5204 // match the number of slices in the clipboard, the entire clipboard text
5205 // is pasted at each cursor.
5206 view.update(cx, |view, cx| {
5207 view.select_ranges(vec![0..0, 31..31], None, cx);
5208 view.handle_input(&Input("( ".into()), cx);
5209 view.paste(&Paste, cx);
5210 view.handle_input(&Input(") ".into()), cx);
5211 assert_eq!(
5212 view.display_text(cx),
5213 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5214 );
5215 });
5216
5217 view.update(cx, |view, cx| {
5218 view.select_ranges(vec![0..0], None, cx);
5219 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5220 assert_eq!(
5221 view.display_text(cx),
5222 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5223 );
5224 });
5225
5226 // Cut with three selections, one of which is full-line.
5227 view.update(cx, |view, cx| {
5228 view.select_display_ranges(
5229 &[
5230 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5231 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5232 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5233 ],
5234 cx,
5235 )
5236 .unwrap();
5237 view.cut(&Cut, cx);
5238 assert_eq!(
5239 view.display_text(cx),
5240 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5241 );
5242 });
5243
5244 // Paste with three selections, noticing how the copied selection that was full-line
5245 // gets inserted before the second cursor.
5246 view.update(cx, |view, cx| {
5247 view.select_display_ranges(
5248 &[
5249 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5250 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5251 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5252 ],
5253 cx,
5254 )
5255 .unwrap();
5256 view.paste(&Paste, cx);
5257 assert_eq!(
5258 view.display_text(cx),
5259 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5260 );
5261 assert_eq!(
5262 view.selected_display_ranges(cx),
5263 &[
5264 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5265 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5266 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5267 ]
5268 );
5269 });
5270
5271 // Copy with a single cursor only, which writes the whole line into the clipboard.
5272 view.update(cx, |view, cx| {
5273 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
5274 .unwrap();
5275 view.copy(&Copy, cx);
5276 });
5277
5278 // Paste with three selections, noticing how the copied full-line selection is inserted
5279 // before the empty selections but replaces the selection that is non-empty.
5280 view.update(cx, |view, cx| {
5281 view.select_display_ranges(
5282 &[
5283 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5284 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5285 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5286 ],
5287 cx,
5288 )
5289 .unwrap();
5290 view.paste(&Paste, cx);
5291 assert_eq!(
5292 view.display_text(cx),
5293 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5294 );
5295 assert_eq!(
5296 view.selected_display_ranges(cx),
5297 &[
5298 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5299 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5300 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5301 ]
5302 );
5303 });
5304 }
5305
5306 #[gpui::test]
5307 fn test_select_all(cx: &mut gpui::MutableAppContext) {
5308 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5309 let settings = EditorSettings::test(&cx);
5310 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5311 view.update(cx, |view, cx| {
5312 view.select_all(&SelectAll, cx);
5313 assert_eq!(
5314 view.selected_display_ranges(cx),
5315 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5316 );
5317 });
5318 }
5319
5320 #[gpui::test]
5321 fn test_select_line(cx: &mut gpui::MutableAppContext) {
5322 let settings = EditorSettings::test(&cx);
5323 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5324 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5325 view.update(cx, |view, cx| {
5326 view.select_display_ranges(
5327 &[
5328 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5329 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5330 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5331 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5332 ],
5333 cx,
5334 )
5335 .unwrap();
5336 view.select_line(&SelectLine, cx);
5337 assert_eq!(
5338 view.selected_display_ranges(cx),
5339 vec![
5340 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5341 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5342 ]
5343 );
5344 });
5345
5346 view.update(cx, |view, cx| {
5347 view.select_line(&SelectLine, cx);
5348 assert_eq!(
5349 view.selected_display_ranges(cx),
5350 vec![
5351 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5352 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5353 ]
5354 );
5355 });
5356
5357 view.update(cx, |view, cx| {
5358 view.select_line(&SelectLine, cx);
5359 assert_eq!(
5360 view.selected_display_ranges(cx),
5361 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5362 );
5363 });
5364 }
5365
5366 #[gpui::test]
5367 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5368 let settings = EditorSettings::test(&cx);
5369 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5370 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5371 view.update(cx, |view, cx| {
5372 view.fold_ranges(
5373 vec![
5374 Point::new(0, 2)..Point::new(1, 2),
5375 Point::new(2, 3)..Point::new(4, 1),
5376 Point::new(7, 0)..Point::new(8, 4),
5377 ],
5378 cx,
5379 );
5380 view.select_display_ranges(
5381 &[
5382 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5383 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5384 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5385 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5386 ],
5387 cx,
5388 )
5389 .unwrap();
5390 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5391 });
5392
5393 view.update(cx, |view, cx| {
5394 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5395 assert_eq!(
5396 view.display_text(cx),
5397 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5398 );
5399 assert_eq!(
5400 view.selected_display_ranges(cx),
5401 [
5402 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5403 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5404 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5405 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5406 ]
5407 );
5408 });
5409
5410 view.update(cx, |view, cx| {
5411 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5412 .unwrap();
5413 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5414 assert_eq!(
5415 view.display_text(cx),
5416 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5417 );
5418 assert_eq!(
5419 view.selected_display_ranges(cx),
5420 [
5421 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5422 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5423 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5424 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5425 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5426 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5427 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5428 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5429 ]
5430 );
5431 });
5432 }
5433
5434 #[gpui::test]
5435 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5436 let settings = EditorSettings::test(&cx);
5437 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5438 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5439
5440 view.update(cx, |view, cx| {
5441 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5442 .unwrap();
5443 });
5444 view.update(cx, |view, cx| {
5445 view.add_selection_above(&AddSelectionAbove, cx);
5446 assert_eq!(
5447 view.selected_display_ranges(cx),
5448 vec![
5449 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5450 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5451 ]
5452 );
5453 });
5454
5455 view.update(cx, |view, cx| {
5456 view.add_selection_above(&AddSelectionAbove, cx);
5457 assert_eq!(
5458 view.selected_display_ranges(cx),
5459 vec![
5460 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5461 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5462 ]
5463 );
5464 });
5465
5466 view.update(cx, |view, cx| {
5467 view.add_selection_below(&AddSelectionBelow, cx);
5468 assert_eq!(
5469 view.selected_display_ranges(cx),
5470 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5471 );
5472 });
5473
5474 view.update(cx, |view, cx| {
5475 view.add_selection_below(&AddSelectionBelow, cx);
5476 assert_eq!(
5477 view.selected_display_ranges(cx),
5478 vec![
5479 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5480 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5481 ]
5482 );
5483 });
5484
5485 view.update(cx, |view, cx| {
5486 view.add_selection_below(&AddSelectionBelow, cx);
5487 assert_eq!(
5488 view.selected_display_ranges(cx),
5489 vec![
5490 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5491 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5492 ]
5493 );
5494 });
5495
5496 view.update(cx, |view, cx| {
5497 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5498 .unwrap();
5499 });
5500 view.update(cx, |view, cx| {
5501 view.add_selection_below(&AddSelectionBelow, cx);
5502 assert_eq!(
5503 view.selected_display_ranges(cx),
5504 vec![
5505 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5506 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5507 ]
5508 );
5509 });
5510
5511 view.update(cx, |view, cx| {
5512 view.add_selection_below(&AddSelectionBelow, cx);
5513 assert_eq!(
5514 view.selected_display_ranges(cx),
5515 vec![
5516 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5517 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5518 ]
5519 );
5520 });
5521
5522 view.update(cx, |view, cx| {
5523 view.add_selection_above(&AddSelectionAbove, cx);
5524 assert_eq!(
5525 view.selected_display_ranges(cx),
5526 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5527 );
5528 });
5529
5530 view.update(cx, |view, cx| {
5531 view.add_selection_above(&AddSelectionAbove, cx);
5532 assert_eq!(
5533 view.selected_display_ranges(cx),
5534 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5535 );
5536 });
5537
5538 view.update(cx, |view, cx| {
5539 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5540 .unwrap();
5541 view.add_selection_below(&AddSelectionBelow, cx);
5542 assert_eq!(
5543 view.selected_display_ranges(cx),
5544 vec![
5545 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5546 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5547 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5548 ]
5549 );
5550 });
5551
5552 view.update(cx, |view, cx| {
5553 view.add_selection_below(&AddSelectionBelow, cx);
5554 assert_eq!(
5555 view.selected_display_ranges(cx),
5556 vec![
5557 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5558 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5559 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5560 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5561 ]
5562 );
5563 });
5564
5565 view.update(cx, |view, cx| {
5566 view.add_selection_above(&AddSelectionAbove, cx);
5567 assert_eq!(
5568 view.selected_display_ranges(cx),
5569 vec![
5570 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5571 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5572 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5573 ]
5574 );
5575 });
5576
5577 view.update(cx, |view, cx| {
5578 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5579 .unwrap();
5580 });
5581 view.update(cx, |view, cx| {
5582 view.add_selection_above(&AddSelectionAbove, cx);
5583 assert_eq!(
5584 view.selected_display_ranges(cx),
5585 vec![
5586 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5587 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5588 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5589 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5590 ]
5591 );
5592 });
5593
5594 view.update(cx, |view, cx| {
5595 view.add_selection_below(&AddSelectionBelow, cx);
5596 assert_eq!(
5597 view.selected_display_ranges(cx),
5598 vec![
5599 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5600 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5601 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5602 ]
5603 );
5604 });
5605 }
5606
5607 #[gpui::test]
5608 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5609 let settings = cx.read(EditorSettings::test);
5610 let language = Some(Arc::new(Language::new(
5611 LanguageConfig::default(),
5612 Some(tree_sitter_rust::language()),
5613 )));
5614
5615 let text = r#"
5616 use mod1::mod2::{mod3, mod4};
5617
5618 fn fn_1(param1: bool, param2: &str) {
5619 let var1 = "text";
5620 }
5621 "#
5622 .unindent();
5623
5624 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5625 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5626 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5627 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5628 .await;
5629
5630 view.update(&mut cx, |view, cx| {
5631 view.select_display_ranges(
5632 &[
5633 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5634 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5635 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5636 ],
5637 cx,
5638 )
5639 .unwrap();
5640 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5641 });
5642 assert_eq!(
5643 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5644 &[
5645 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5646 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5647 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5648 ]
5649 );
5650
5651 view.update(&mut cx, |view, cx| {
5652 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5653 });
5654 assert_eq!(
5655 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5656 &[
5657 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5658 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5659 ]
5660 );
5661
5662 view.update(&mut cx, |view, cx| {
5663 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5664 });
5665 assert_eq!(
5666 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5667 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5668 );
5669
5670 // Trying to expand the selected syntax node one more time has no effect.
5671 view.update(&mut cx, |view, cx| {
5672 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5673 });
5674 assert_eq!(
5675 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5676 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5677 );
5678
5679 view.update(&mut cx, |view, cx| {
5680 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5681 });
5682 assert_eq!(
5683 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5684 &[
5685 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5686 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5687 ]
5688 );
5689
5690 view.update(&mut cx, |view, cx| {
5691 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5692 });
5693 assert_eq!(
5694 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5695 &[
5696 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5697 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5698 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5699 ]
5700 );
5701
5702 view.update(&mut cx, |view, cx| {
5703 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5704 });
5705 assert_eq!(
5706 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5707 &[
5708 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5709 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5710 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5711 ]
5712 );
5713
5714 // Trying to shrink the selected syntax node one more time has no effect.
5715 view.update(&mut cx, |view, cx| {
5716 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5717 });
5718 assert_eq!(
5719 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5720 &[
5721 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5722 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5723 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5724 ]
5725 );
5726
5727 // Ensure that we keep expanding the selection if the larger selection starts or ends within
5728 // a fold.
5729 view.update(&mut cx, |view, cx| {
5730 view.fold_ranges(
5731 vec![
5732 Point::new(0, 21)..Point::new(0, 24),
5733 Point::new(3, 20)..Point::new(3, 22),
5734 ],
5735 cx,
5736 );
5737 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5738 });
5739 assert_eq!(
5740 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5741 &[
5742 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5743 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5744 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5745 ]
5746 );
5747 }
5748
5749 #[gpui::test]
5750 async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
5751 let settings = cx.read(EditorSettings::test);
5752 let language = Some(Arc::new(
5753 Language::new(
5754 LanguageConfig {
5755 brackets: vec![
5756 BracketPair {
5757 start: "{".to_string(),
5758 end: "}".to_string(),
5759 close: false,
5760 newline: true,
5761 },
5762 BracketPair {
5763 start: "(".to_string(),
5764 end: ")".to_string(),
5765 close: false,
5766 newline: true,
5767 },
5768 ],
5769 ..Default::default()
5770 },
5771 Some(tree_sitter_rust::language()),
5772 )
5773 .with_indents_query(
5774 r#"
5775 (_ "(" ")" @end) @indent
5776 (_ "{" "}" @end) @indent
5777 "#,
5778 )
5779 .unwrap(),
5780 ));
5781
5782 let text = "fn a() {}";
5783
5784 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5785 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5786 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5787 editor
5788 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
5789 .await;
5790
5791 editor.update(&mut cx, |editor, cx| {
5792 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
5793 editor.newline(&Newline, cx);
5794 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
5795 assert_eq!(
5796 editor.selected_ranges(cx),
5797 &[
5798 Point::new(1, 4)..Point::new(1, 4),
5799 Point::new(3, 4)..Point::new(3, 4),
5800 Point::new(5, 0)..Point::new(5, 0)
5801 ]
5802 );
5803 });
5804 }
5805
5806 #[gpui::test]
5807 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5808 let settings = cx.read(EditorSettings::test);
5809 let language = Some(Arc::new(Language::new(
5810 LanguageConfig {
5811 brackets: vec![
5812 BracketPair {
5813 start: "{".to_string(),
5814 end: "}".to_string(),
5815 close: true,
5816 newline: true,
5817 },
5818 BracketPair {
5819 start: "/*".to_string(),
5820 end: " */".to_string(),
5821 close: true,
5822 newline: true,
5823 },
5824 ],
5825 ..Default::default()
5826 },
5827 Some(tree_sitter_rust::language()),
5828 )));
5829
5830 let text = r#"
5831 a
5832
5833 /
5834
5835 "#
5836 .unindent();
5837
5838 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5839 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5840 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5841 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5842 .await;
5843
5844 view.update(&mut cx, |view, cx| {
5845 view.select_display_ranges(
5846 &[
5847 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5848 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5849 ],
5850 cx,
5851 )
5852 .unwrap();
5853 view.handle_input(&Input("{".to_string()), cx);
5854 view.handle_input(&Input("{".to_string()), cx);
5855 view.handle_input(&Input("{".to_string()), cx);
5856 assert_eq!(
5857 view.text(cx),
5858 "
5859 {{{}}}
5860 {{{}}}
5861 /
5862
5863 "
5864 .unindent()
5865 );
5866
5867 view.move_right(&MoveRight, cx);
5868 view.handle_input(&Input("}".to_string()), cx);
5869 view.handle_input(&Input("}".to_string()), cx);
5870 view.handle_input(&Input("}".to_string()), cx);
5871 assert_eq!(
5872 view.text(cx),
5873 "
5874 {{{}}}}
5875 {{{}}}}
5876 /
5877
5878 "
5879 .unindent()
5880 );
5881
5882 view.undo(&Undo, cx);
5883 view.handle_input(&Input("/".to_string()), cx);
5884 view.handle_input(&Input("*".to_string()), cx);
5885 assert_eq!(
5886 view.text(cx),
5887 "
5888 /* */
5889 /* */
5890 /
5891
5892 "
5893 .unindent()
5894 );
5895
5896 view.undo(&Undo, cx);
5897 view.select_display_ranges(
5898 &[
5899 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5900 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5901 ],
5902 cx,
5903 )
5904 .unwrap();
5905 view.handle_input(&Input("*".to_string()), cx);
5906 assert_eq!(
5907 view.text(cx),
5908 "
5909 a
5910
5911 /*
5912 *
5913 "
5914 .unindent()
5915 );
5916 });
5917 }
5918
5919 #[gpui::test]
5920 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5921 let settings = cx.read(EditorSettings::test);
5922 let language = Some(Arc::new(Language::new(
5923 LanguageConfig {
5924 line_comment: Some("// ".to_string()),
5925 ..Default::default()
5926 },
5927 Some(tree_sitter_rust::language()),
5928 )));
5929
5930 let text = "
5931 fn a() {
5932 //b();
5933 // c();
5934 // d();
5935 }
5936 "
5937 .unindent();
5938
5939 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5940 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5941 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5942
5943 view.update(&mut cx, |editor, cx| {
5944 // If multiple selections intersect a line, the line is only
5945 // toggled once.
5946 editor
5947 .select_display_ranges(
5948 &[
5949 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5950 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5951 ],
5952 cx,
5953 )
5954 .unwrap();
5955 editor.toggle_comments(&ToggleComments, cx);
5956 assert_eq!(
5957 editor.text(cx),
5958 "
5959 fn a() {
5960 b();
5961 c();
5962 d();
5963 }
5964 "
5965 .unindent()
5966 );
5967
5968 // The comment prefix is inserted at the same column for every line
5969 // in a selection.
5970 editor
5971 .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5972 .unwrap();
5973 editor.toggle_comments(&ToggleComments, cx);
5974 assert_eq!(
5975 editor.text(cx),
5976 "
5977 fn a() {
5978 // b();
5979 // c();
5980 // d();
5981 }
5982 "
5983 .unindent()
5984 );
5985
5986 // If a selection ends at the beginning of a line, that line is not toggled.
5987 editor
5988 .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
5989 .unwrap();
5990 editor.toggle_comments(&ToggleComments, cx);
5991 assert_eq!(
5992 editor.text(cx),
5993 "
5994 fn a() {
5995 // b();
5996 c();
5997 // d();
5998 }
5999 "
6000 .unindent()
6001 );
6002 });
6003 }
6004
6005 #[gpui::test]
6006 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
6007 let settings = EditorSettings::test(cx);
6008 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6009 let multibuffer = cx.add_model(|cx| {
6010 let mut multibuffer = MultiBuffer::new(0);
6011 multibuffer.push_excerpt(
6012 ExcerptProperties {
6013 buffer: &buffer,
6014 range: Point::new(0, 0)..Point::new(0, 4),
6015 },
6016 cx,
6017 );
6018 multibuffer.push_excerpt(
6019 ExcerptProperties {
6020 buffer: &buffer,
6021 range: Point::new(1, 0)..Point::new(1, 4),
6022 },
6023 cx,
6024 );
6025 multibuffer
6026 });
6027
6028 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
6029
6030 let (_, view) = cx.add_window(Default::default(), |cx| {
6031 build_editor(multibuffer, settings, cx)
6032 });
6033 view.update(cx, |view, cx| {
6034 view.select_display_ranges(
6035 &[
6036 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6037 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6038 ],
6039 cx,
6040 )
6041 .unwrap();
6042
6043 view.handle_input(&Input("X".to_string()), cx);
6044 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
6045 assert_eq!(
6046 view.selected_display_ranges(cx),
6047 &[
6048 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6049 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6050 ]
6051 )
6052 });
6053 }
6054
6055 #[gpui::test]
6056 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
6057 let settings = EditorSettings::test(cx);
6058 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6059 let multibuffer = cx.add_model(|cx| {
6060 let mut multibuffer = MultiBuffer::new(0);
6061 multibuffer.push_excerpt(
6062 ExcerptProperties {
6063 buffer: &buffer,
6064 range: Point::new(0, 0)..Point::new(1, 4),
6065 },
6066 cx,
6067 );
6068 multibuffer.push_excerpt(
6069 ExcerptProperties {
6070 buffer: &buffer,
6071 range: Point::new(1, 0)..Point::new(2, 4),
6072 },
6073 cx,
6074 );
6075 multibuffer
6076 });
6077
6078 assert_eq!(
6079 multibuffer.read(cx).read(cx).text(),
6080 "aaaa\nbbbb\nbbbb\ncccc"
6081 );
6082
6083 let (_, view) = cx.add_window(Default::default(), |cx| {
6084 build_editor(multibuffer, settings, cx)
6085 });
6086 view.update(cx, |view, cx| {
6087 view.select_display_ranges(
6088 &[
6089 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6090 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6091 ],
6092 cx,
6093 )
6094 .unwrap();
6095
6096 view.handle_input(&Input("X".to_string()), cx);
6097 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
6098 assert_eq!(
6099 view.selected_display_ranges(cx),
6100 &[
6101 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6102 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6103 ]
6104 )
6105 });
6106 }
6107
6108 #[gpui::test]
6109 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
6110 let settings = cx.read(EditorSettings::test);
6111 let language = Some(Arc::new(Language::new(
6112 LanguageConfig {
6113 brackets: vec![
6114 BracketPair {
6115 start: "{".to_string(),
6116 end: "}".to_string(),
6117 close: true,
6118 newline: true,
6119 },
6120 BracketPair {
6121 start: "/* ".to_string(),
6122 end: " */".to_string(),
6123 close: true,
6124 newline: true,
6125 },
6126 ],
6127 ..Default::default()
6128 },
6129 Some(tree_sitter_rust::language()),
6130 )));
6131
6132 let text = concat!(
6133 "{ }\n", // Suppress rustfmt
6134 " x\n", //
6135 " /* */\n", //
6136 "x\n", //
6137 "{{} }\n", //
6138 );
6139
6140 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
6141 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6142 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6143 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6144 .await;
6145
6146 view.update(&mut cx, |view, cx| {
6147 view.select_display_ranges(
6148 &[
6149 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6150 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6151 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6152 ],
6153 cx,
6154 )
6155 .unwrap();
6156 view.newline(&Newline, cx);
6157
6158 assert_eq!(
6159 view.buffer().read(cx).read(cx).text(),
6160 concat!(
6161 "{ \n", // Suppress rustfmt
6162 "\n", //
6163 "}\n", //
6164 " x\n", //
6165 " /* \n", //
6166 " \n", //
6167 " */\n", //
6168 "x\n", //
6169 "{{} \n", //
6170 "}\n", //
6171 )
6172 );
6173 });
6174 }
6175
6176 impl Editor {
6177 fn selected_ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
6178 &self,
6179 cx: &mut MutableAppContext,
6180 ) -> Vec<Range<D>> {
6181 self.local_selections::<D>(cx)
6182 .iter()
6183 .map(|s| {
6184 if s.reversed {
6185 s.end.clone()..s.start.clone()
6186 } else {
6187 s.start.clone()..s.end.clone()
6188 }
6189 })
6190 .collect()
6191 }
6192
6193 fn selected_display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
6194 let display_map = self
6195 .display_map
6196 .update(cx, |display_map, cx| display_map.snapshot(cx));
6197 self.selections
6198 .iter()
6199 .chain(
6200 self.pending_selection
6201 .as_ref()
6202 .map(|pending| &pending.selection),
6203 )
6204 .map(|s| {
6205 if s.reversed {
6206 s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
6207 } else {
6208 s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
6209 }
6210 })
6211 .collect()
6212 }
6213 }
6214
6215 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
6216 let point = DisplayPoint::new(row as u32, column as u32);
6217 point..point
6218 }
6219
6220 fn build_editor(
6221 buffer: ModelHandle<MultiBuffer>,
6222 settings: EditorSettings,
6223 cx: &mut ViewContext<Editor>,
6224 ) -> Editor {
6225 Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), cx)
6226 }
6227}
6228
6229trait RangeExt<T> {
6230 fn sorted(&self) -> Range<T>;
6231 fn to_inclusive(&self) -> RangeInclusive<T>;
6232}
6233
6234impl<T: Ord + Clone> RangeExt<T> for Range<T> {
6235 fn sorted(&self) -> Self {
6236 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
6237 }
6238
6239 fn to_inclusive(&self) -> RangeInclusive<T> {
6240 self.start.clone()..=self.end.clone()
6241 }
6242}