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