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