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