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