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: AnchorRangeSet,
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);
1296 let new_autoclose_pair_state = self.buffer.update(cx, |buffer, cx| {
1297 let buffer_snapshot = buffer.snapshot(cx);
1298 let autoclose_pair = buffer_snapshot.language().and_then(|language| {
1299 let first_selection_start = selections.first().unwrap().start;
1300 let pair = language.brackets().iter().find(|pair| {
1301 buffer_snapshot.contains_str_at(
1302 first_selection_start.saturating_sub(pair.start.len()),
1303 &pair.start,
1304 )
1305 });
1306 pair.and_then(|pair| {
1307 let should_autoclose = selections[1..].iter().all(|selection| {
1308 buffer_snapshot.contains_str_at(
1309 selection.start.saturating_sub(pair.start.len()),
1310 &pair.start,
1311 )
1312 });
1313
1314 if should_autoclose {
1315 Some(pair.clone())
1316 } else {
1317 None
1318 }
1319 })
1320 });
1321
1322 autoclose_pair.and_then(|pair| {
1323 let selection_ranges = selections
1324 .iter()
1325 .map(|selection| {
1326 let start = selection.start.to_offset(&buffer_snapshot);
1327 start..start
1328 })
1329 .collect::<SmallVec<[_; 32]>>();
1330
1331 buffer.edit(selection_ranges, &pair.end, cx);
1332
1333 if pair.end.len() == 1 {
1334 let mut delta = 0;
1335 Some(BracketPairState {
1336 ranges: buffer.anchor_range_set(
1337 Bias::Left,
1338 Bias::Right,
1339 selections.iter().map(move |selection| {
1340 let offset = selection.start + delta;
1341 delta += 1;
1342 offset..offset
1343 }),
1344 ),
1345 pair,
1346 })
1347 } else {
1348 None
1349 }
1350 })
1351 });
1352 self.autoclose_stack.extend(new_autoclose_pair_state);
1353 }
1354
1355 fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
1356 let old_selections = self.selections::<usize>(cx);
1357 let autoclose_pair_state = if let Some(autoclose_pair_state) = self.autoclose_stack.last() {
1358 autoclose_pair_state
1359 } else {
1360 return false;
1361 };
1362 if text != autoclose_pair_state.pair.end {
1363 return false;
1364 }
1365
1366 debug_assert_eq!(old_selections.len(), autoclose_pair_state.ranges.len());
1367
1368 let buffer = self.buffer.read(cx).snapshot(cx);
1369 if old_selections
1370 .iter()
1371 .zip(autoclose_pair_state.ranges.ranges::<usize>(&buffer))
1372 .all(|(selection, autoclose_range)| {
1373 let autoclose_range_end = autoclose_range.end.to_offset(&buffer);
1374 selection.is_empty() && selection.start == autoclose_range_end
1375 })
1376 {
1377 let new_selections = old_selections
1378 .into_iter()
1379 .map(|selection| {
1380 let cursor = selection.start + 1;
1381 Selection {
1382 id: selection.id,
1383 start: cursor,
1384 end: cursor,
1385 reversed: false,
1386 goal: SelectionGoal::None,
1387 }
1388 })
1389 .collect();
1390 self.autoclose_stack.pop();
1391 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1392 true
1393 } else {
1394 false
1395 }
1396 }
1397
1398 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
1399 self.start_transaction(cx);
1400 self.select_all(&SelectAll, cx);
1401 self.insert("", cx);
1402 self.end_transaction(cx);
1403 }
1404
1405 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
1406 self.start_transaction(cx);
1407 let mut selections = self.selections::<Point>(cx);
1408 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1409 for selection in &mut selections {
1410 if selection.is_empty() {
1411 let head = selection.head().to_display_point(&display_map);
1412 let cursor = movement::left(&display_map, head)
1413 .unwrap()
1414 .to_point(&display_map);
1415 selection.set_head(cursor);
1416 selection.goal = SelectionGoal::None;
1417 }
1418 }
1419 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1420 self.insert("", cx);
1421 self.end_transaction(cx);
1422 }
1423
1424 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
1425 self.start_transaction(cx);
1426 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1427 let mut selections = self.selections::<Point>(cx);
1428 for selection in &mut selections {
1429 if selection.is_empty() {
1430 let head = selection.head().to_display_point(&display_map);
1431 let cursor = movement::right(&display_map, head)
1432 .unwrap()
1433 .to_point(&display_map);
1434 selection.set_head(cursor);
1435 selection.goal = SelectionGoal::None;
1436 }
1437 }
1438 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1439 self.insert(&"", cx);
1440 self.end_transaction(cx);
1441 }
1442
1443 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
1444 self.start_transaction(cx);
1445 let tab_size = self.build_settings.borrow()(cx).tab_size;
1446 let mut selections = self.selections::<Point>(cx);
1447 let mut last_indent = None;
1448 self.buffer.update(cx, |buffer, cx| {
1449 for selection in &mut selections {
1450 if selection.is_empty() {
1451 let char_column = buffer
1452 .as_snapshot()
1453 .text_for_range(Point::new(selection.start.row, 0)..selection.start)
1454 .flat_map(str::chars)
1455 .count();
1456 let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
1457 buffer.edit(
1458 [selection.start..selection.start],
1459 " ".repeat(chars_to_next_tab_stop),
1460 cx,
1461 );
1462 selection.start.column += chars_to_next_tab_stop as u32;
1463 selection.end = selection.start;
1464 } else {
1465 let mut start_row = selection.start.row;
1466 let mut end_row = selection.end.row + 1;
1467
1468 // If a selection ends at the beginning of a line, don't indent
1469 // that last line.
1470 if selection.end.column == 0 {
1471 end_row -= 1;
1472 }
1473
1474 // Avoid re-indenting a row that has already been indented by a
1475 // previous selection, but still update this selection's column
1476 // to reflect that indentation.
1477 if let Some((last_indent_row, last_indent_len)) = last_indent {
1478 if last_indent_row == selection.start.row {
1479 selection.start.column += last_indent_len;
1480 start_row += 1;
1481 }
1482 if last_indent_row == selection.end.row {
1483 selection.end.column += last_indent_len;
1484 }
1485 }
1486
1487 for row in start_row..end_row {
1488 let indent_column = buffer.indent_column_for_line(row) as usize;
1489 let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
1490 let row_start = Point::new(row, 0);
1491 buffer.edit(
1492 [row_start..row_start],
1493 " ".repeat(columns_to_next_tab_stop),
1494 cx,
1495 );
1496
1497 // Update this selection's endpoints to reflect the indentation.
1498 if row == selection.start.row {
1499 selection.start.column += columns_to_next_tab_stop as u32;
1500 }
1501 if row == selection.end.row {
1502 selection.end.column += columns_to_next_tab_stop as u32;
1503 }
1504
1505 last_indent = Some((row, columns_to_next_tab_stop as u32));
1506 }
1507 }
1508 }
1509 });
1510
1511 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1512 self.end_transaction(cx);
1513 }
1514
1515 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
1516 self.start_transaction(cx);
1517 let tab_size = self.build_settings.borrow()(cx).tab_size;
1518 let selections = self.selections::<Point>(cx);
1519 let mut deletion_ranges = Vec::new();
1520 let mut last_outdent = None;
1521 self.buffer.update(cx, |buffer, cx| {
1522 for selection in &selections {
1523 let mut start_row = selection.start.row;
1524 let mut end_row = selection.end.row + 1;
1525
1526 // If a selection ends at the beginning of a line, don't indent
1527 // that last line.
1528 if selection.end.column == 0 {
1529 end_row -= 1;
1530 }
1531
1532 // Avoid re-outdenting a row that has already been outdented by a
1533 // previous selection.
1534 if let Some(last_row) = last_outdent {
1535 if last_row == selection.start.row {
1536 start_row += 1;
1537 }
1538 }
1539
1540 for row in start_row..end_row {
1541 let column = buffer.indent_column_for_line(row) as usize;
1542 if column > 0 {
1543 let mut deletion_len = (column % tab_size) as u32;
1544 if deletion_len == 0 {
1545 deletion_len = tab_size as u32;
1546 }
1547 deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
1548 last_outdent = Some(row);
1549 }
1550 }
1551 }
1552 buffer.edit(deletion_ranges, "", cx);
1553 });
1554
1555 self.update_selections(self.selections::<usize>(cx), Some(Autoscroll::Fit), cx);
1556 self.end_transaction(cx);
1557 }
1558
1559 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
1560 self.start_transaction(cx);
1561
1562 let selections = self.selections::<Point>(cx);
1563 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1564 let buffer = self.buffer.read(cx).snapshot(cx);
1565
1566 let mut row_delta = 0;
1567 let mut new_cursors = Vec::new();
1568 let mut edit_ranges = Vec::new();
1569 let mut selections = selections.iter().peekable();
1570 while let Some(selection) = selections.next() {
1571 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1572 let goal_display_column = selection.head().to_display_point(&display_map).column();
1573
1574 // Accumulate contiguous regions of rows that we want to delete.
1575 while let Some(next_selection) = selections.peek() {
1576 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1577 if next_rows.start <= rows.end {
1578 rows.end = next_rows.end;
1579 selections.next().unwrap();
1580 } else {
1581 break;
1582 }
1583 }
1584
1585 let mut edit_start = Point::new(rows.start, 0).to_offset(&buffer);
1586 let edit_end;
1587 let cursor_buffer_row;
1588 if buffer.max_point().row >= rows.end {
1589 // If there's a line after the range, delete the \n from the end of the row range
1590 // and position the cursor on the next line.
1591 edit_end = Point::new(rows.end, 0).to_offset(&buffer);
1592 cursor_buffer_row = rows.start;
1593 } else {
1594 // If there isn't a line after the range, delete the \n from the line before the
1595 // start of the row range and position the cursor there.
1596 edit_start = edit_start.saturating_sub(1);
1597 edit_end = buffer.len();
1598 cursor_buffer_row = rows.start.saturating_sub(1);
1599 }
1600
1601 let mut cursor =
1602 Point::new(cursor_buffer_row - row_delta, 0).to_display_point(&display_map);
1603 *cursor.column_mut() =
1604 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
1605 row_delta += rows.len() as u32;
1606
1607 new_cursors.push((selection.id, cursor.to_point(&display_map)));
1608 edit_ranges.push(edit_start..edit_end);
1609 }
1610
1611 new_cursors.sort_unstable_by_key(|(_, point)| point.clone());
1612 let new_selections = new_cursors
1613 .into_iter()
1614 .map(|(id, cursor)| Selection {
1615 id,
1616 start: cursor,
1617 end: cursor,
1618 reversed: false,
1619 goal: SelectionGoal::None,
1620 })
1621 .collect();
1622 self.buffer
1623 .update(cx, |buffer, cx| buffer.edit(edit_ranges, "", cx));
1624 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1625 self.end_transaction(cx);
1626 }
1627
1628 pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
1629 self.start_transaction(cx);
1630
1631 let mut selections = self.selections::<Point>(cx);
1632 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1633 let buffer = self.buffer.read(cx);
1634
1635 let mut edits = Vec::new();
1636 let mut selections_iter = selections.iter().peekable();
1637 while let Some(selection) = selections_iter.next() {
1638 // Avoid duplicating the same lines twice.
1639 let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1640
1641 while let Some(next_selection) = selections_iter.peek() {
1642 let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1643 if next_rows.start <= rows.end - 1 {
1644 rows.end = next_rows.end;
1645 selections_iter.next().unwrap();
1646 } else {
1647 break;
1648 }
1649 }
1650
1651 // Copy the text from the selected row region and splice it at the start of the region.
1652 let start = Point::new(rows.start, 0);
1653 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
1654 let text = buffer
1655 .text_for_range(start..end)
1656 .chain(Some("\n"))
1657 .collect::<String>();
1658 edits.push((start, text, rows.len() as u32));
1659 }
1660
1661 let mut edits_iter = edits.iter().peekable();
1662 let mut row_delta = 0;
1663 for selection in selections.iter_mut() {
1664 while let Some((point, _, line_count)) = edits_iter.peek() {
1665 if *point <= selection.start {
1666 row_delta += line_count;
1667 edits_iter.next();
1668 } else {
1669 break;
1670 }
1671 }
1672 selection.start.row += row_delta;
1673 selection.end.row += row_delta;
1674 }
1675
1676 self.buffer.update(cx, |buffer, cx| {
1677 for (point, text, _) in edits.into_iter().rev() {
1678 buffer.edit(Some(point..point), text, cx);
1679 }
1680 });
1681
1682 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1683 self.end_transaction(cx);
1684 }
1685
1686 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
1687 self.start_transaction(cx);
1688
1689 let selections = self.selections::<Point>(cx);
1690 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1691 let buffer = self.buffer.read(cx).snapshot(cx);
1692
1693 let mut edits = Vec::new();
1694 let mut new_selection_ranges = Vec::new();
1695 let mut old_folds = Vec::new();
1696 let mut new_folds = Vec::new();
1697
1698 let mut selections = selections.iter().peekable();
1699 let mut contiguous_selections = Vec::new();
1700 while let Some(selection) = selections.next() {
1701 // Accumulate contiguous regions of rows that we want to move.
1702 contiguous_selections.push(selection.point_range(&buffer));
1703 let SpannedRows {
1704 mut buffer_rows,
1705 mut display_rows,
1706 } = selection.spanned_rows(false, &display_map);
1707
1708 while let Some(next_selection) = selections.peek() {
1709 let SpannedRows {
1710 buffer_rows: next_buffer_rows,
1711 display_rows: next_display_rows,
1712 } = next_selection.spanned_rows(false, &display_map);
1713 if next_buffer_rows.start <= buffer_rows.end {
1714 buffer_rows.end = next_buffer_rows.end;
1715 display_rows.end = next_display_rows.end;
1716 contiguous_selections.push(next_selection.point_range(&buffer));
1717 selections.next().unwrap();
1718 } else {
1719 break;
1720 }
1721 }
1722
1723 // Cut the text from the selected rows and paste it at the start of the previous line.
1724 if display_rows.start != 0 {
1725 let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1726 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1727 .to_offset(&buffer);
1728
1729 let prev_row_display_start = DisplayPoint::new(display_rows.start - 1, 0);
1730 let prev_row_buffer_start = display_map.prev_row_boundary(prev_row_display_start).1;
1731 let prev_row_buffer_start_offset = prev_row_buffer_start.to_offset(&buffer);
1732
1733 let mut text = String::new();
1734 text.extend(buffer.text_for_range(start..end));
1735 text.push('\n');
1736 edits.push((
1737 prev_row_buffer_start_offset..prev_row_buffer_start_offset,
1738 text,
1739 ));
1740 edits.push((start - 1..end, String::new()));
1741
1742 let row_delta = buffer_rows.start - prev_row_buffer_start.row;
1743
1744 // Move selections up.
1745 for range in &mut contiguous_selections {
1746 range.start.row -= row_delta;
1747 range.end.row -= row_delta;
1748 }
1749
1750 // Move folds up.
1751 old_folds.push(start..end);
1752 for fold in display_map.folds_in_range(start..end) {
1753 let mut start = fold.start.to_point(&buffer);
1754 let mut end = fold.end.to_point(&buffer);
1755 start.row -= row_delta;
1756 end.row -= row_delta;
1757 new_folds.push(start..end);
1758 }
1759 }
1760
1761 new_selection_ranges.extend(contiguous_selections.drain(..));
1762 }
1763
1764 self.unfold_ranges(old_folds, cx);
1765 self.buffer.update(cx, |buffer, cx| {
1766 for (range, text) in edits.into_iter().rev() {
1767 buffer.edit(Some(range), text, cx);
1768 }
1769 });
1770 self.fold_ranges(new_folds, cx);
1771 self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1772
1773 self.end_transaction(cx);
1774 }
1775
1776 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1777 self.start_transaction(cx);
1778
1779 let selections = self.selections::<Point>(cx);
1780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1781 let buffer = self.buffer.read(cx).snapshot(cx);
1782
1783 let mut edits = Vec::new();
1784 let mut new_selection_ranges = Vec::new();
1785 let mut old_folds = Vec::new();
1786 let mut new_folds = Vec::new();
1787
1788 let mut selections = selections.iter().peekable();
1789 let mut contiguous_selections = Vec::new();
1790 while let Some(selection) = selections.next() {
1791 // Accumulate contiguous regions of rows that we want to move.
1792 contiguous_selections.push(selection.point_range(&buffer));
1793 let SpannedRows {
1794 mut buffer_rows,
1795 mut display_rows,
1796 } = selection.spanned_rows(false, &display_map);
1797 while let Some(next_selection) = selections.peek() {
1798 let SpannedRows {
1799 buffer_rows: next_buffer_rows,
1800 display_rows: next_display_rows,
1801 } = next_selection.spanned_rows(false, &display_map);
1802 if next_buffer_rows.start <= buffer_rows.end {
1803 buffer_rows.end = next_buffer_rows.end;
1804 display_rows.end = next_display_rows.end;
1805 contiguous_selections.push(next_selection.point_range(&buffer));
1806 selections.next().unwrap();
1807 } else {
1808 break;
1809 }
1810 }
1811
1812 // Cut the text from the selected rows and paste it at the end of the next line.
1813 if display_rows.end <= display_map.max_point().row() {
1814 let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1815 let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1816 .to_offset(&buffer);
1817
1818 let next_row_display_end =
1819 DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1820 let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1821 let next_row_buffer_end_offset = next_row_buffer_end.to_offset(&buffer);
1822
1823 let mut text = String::new();
1824 text.push('\n');
1825 text.extend(buffer.text_for_range(start..end));
1826 edits.push((start..end + 1, String::new()));
1827 edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1828
1829 let row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1830
1831 // Move selections down.
1832 for range in &mut contiguous_selections {
1833 range.start.row += row_delta;
1834 range.end.row += row_delta;
1835 }
1836
1837 // Move folds down.
1838 old_folds.push(start..end);
1839 for fold in display_map.folds_in_range(start..end) {
1840 let mut start = fold.start.to_point(&buffer);
1841 let mut end = fold.end.to_point(&buffer);
1842 start.row += row_delta;
1843 end.row += row_delta;
1844 new_folds.push(start..end);
1845 }
1846 }
1847
1848 new_selection_ranges.extend(contiguous_selections.drain(..));
1849 }
1850
1851 self.unfold_ranges(old_folds, cx);
1852 self.buffer.update(cx, |buffer, cx| {
1853 for (range, text) in edits.into_iter().rev() {
1854 buffer.edit(Some(range), text, cx);
1855 }
1856 });
1857 self.fold_ranges(new_folds, cx);
1858 self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1859
1860 self.end_transaction(cx);
1861 }
1862
1863 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1864 self.start_transaction(cx);
1865 let mut text = String::new();
1866 let mut selections = self.selections::<Point>(cx);
1867 let mut clipboard_selections = Vec::with_capacity(selections.len());
1868 {
1869 let buffer = self.buffer.read(cx);
1870 let max_point = buffer.max_point();
1871 for selection in &mut selections {
1872 let is_entire_line = selection.is_empty();
1873 if is_entire_line {
1874 selection.start = Point::new(selection.start.row, 0);
1875 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
1876 }
1877 let mut len = 0;
1878 for chunk in buffer.text_for_range(selection.start..selection.end) {
1879 text.push_str(chunk);
1880 len += chunk.len();
1881 }
1882 clipboard_selections.push(ClipboardSelection {
1883 len,
1884 is_entire_line,
1885 });
1886 }
1887 }
1888 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1889 self.insert("", cx);
1890 self.end_transaction(cx);
1891
1892 cx.as_mut()
1893 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1894 }
1895
1896 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1897 let selections = self.selections::<Point>(cx);
1898 let buffer = self.buffer.read(cx);
1899 let max_point = buffer.max_point();
1900 let mut text = String::new();
1901 let mut clipboard_selections = Vec::with_capacity(selections.len());
1902 for selection in selections.iter() {
1903 let mut start = selection.start;
1904 let mut end = selection.end;
1905 let is_entire_line = selection.is_empty();
1906 if is_entire_line {
1907 start = Point::new(start.row, 0);
1908 end = cmp::min(max_point, Point::new(start.row + 1, 0));
1909 }
1910 let mut len = 0;
1911 for chunk in buffer.text_for_range(start..end) {
1912 text.push_str(chunk);
1913 len += chunk.len();
1914 }
1915 clipboard_selections.push(ClipboardSelection {
1916 len,
1917 is_entire_line,
1918 });
1919 }
1920
1921 cx.as_mut()
1922 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1923 }
1924
1925 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1926 if let Some(item) = cx.as_mut().read_from_clipboard() {
1927 let clipboard_text = item.text();
1928 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1929 let mut selections = self.selections::<usize>(cx);
1930 let all_selections_were_entire_line =
1931 clipboard_selections.iter().all(|s| s.is_entire_line);
1932 if clipboard_selections.len() != selections.len() {
1933 clipboard_selections.clear();
1934 }
1935
1936 let mut delta = 0_isize;
1937 let mut start_offset = 0;
1938 for (i, selection) in selections.iter_mut().enumerate() {
1939 let to_insert;
1940 let entire_line;
1941 if let Some(clipboard_selection) = clipboard_selections.get(i) {
1942 let end_offset = start_offset + clipboard_selection.len;
1943 to_insert = &clipboard_text[start_offset..end_offset];
1944 entire_line = clipboard_selection.is_entire_line;
1945 start_offset = end_offset
1946 } else {
1947 to_insert = clipboard_text.as_str();
1948 entire_line = all_selections_were_entire_line;
1949 }
1950
1951 selection.start = (selection.start as isize + delta) as usize;
1952 selection.end = (selection.end as isize + delta) as usize;
1953
1954 self.buffer.update(cx, |buffer, cx| {
1955 // If the corresponding selection was empty when this slice of the
1956 // clipboard text was written, then the entire line containing the
1957 // selection was copied. If this selection is also currently empty,
1958 // then paste the line before the current line of the buffer.
1959 let range = if selection.is_empty() && entire_line {
1960 let column =
1961 selection.start.to_point(&*buffer.as_snapshot()).column as usize;
1962 let line_start = selection.start - column;
1963 line_start..line_start
1964 } else {
1965 selection.start..selection.end
1966 };
1967
1968 delta += to_insert.len() as isize - range.len() as isize;
1969 buffer.edit([range], to_insert, cx);
1970 selection.start += to_insert.len();
1971 selection.end = selection.start;
1972 });
1973 }
1974 self.update_selections(selections, Some(Autoscroll::Fit), cx);
1975 } else {
1976 self.insert(clipboard_text, cx);
1977 }
1978 }
1979 }
1980
1981 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1982 self.buffer.update(cx, |buffer, cx| buffer.undo(cx));
1983 self.request_autoscroll(Autoscroll::Fit, cx);
1984 }
1985
1986 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
1987 self.buffer.update(cx, |buffer, cx| buffer.redo(cx));
1988 self.request_autoscroll(Autoscroll::Fit, cx);
1989 }
1990
1991 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
1992 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1993 let mut selections = self.selections::<Point>(cx);
1994 for selection in &mut selections {
1995 let start = selection.start.to_display_point(&display_map);
1996 let end = selection.end.to_display_point(&display_map);
1997
1998 if start != end {
1999 selection.end = selection.start.clone();
2000 } else {
2001 let cursor = movement::left(&display_map, start)
2002 .unwrap()
2003 .to_point(&display_map);
2004 selection.start = cursor.clone();
2005 selection.end = cursor;
2006 }
2007 selection.reversed = false;
2008 selection.goal = SelectionGoal::None;
2009 }
2010 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2011 }
2012
2013 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2015 let mut selections = self.selections::<Point>(cx);
2016 for selection in &mut selections {
2017 let head = selection.head().to_display_point(&display_map);
2018 let cursor = movement::left(&display_map, head)
2019 .unwrap()
2020 .to_point(&display_map);
2021 selection.set_head(cursor);
2022 selection.goal = SelectionGoal::None;
2023 }
2024 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2025 }
2026
2027 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2028 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2029 let mut selections = self.selections::<Point>(cx);
2030 for selection in &mut selections {
2031 let start = selection.start.to_display_point(&display_map);
2032 let end = selection.end.to_display_point(&display_map);
2033
2034 if start != end {
2035 selection.start = selection.end.clone();
2036 } else {
2037 let cursor = movement::right(&display_map, end)
2038 .unwrap()
2039 .to_point(&display_map);
2040 selection.start = cursor;
2041 selection.end = cursor;
2042 }
2043 selection.reversed = false;
2044 selection.goal = SelectionGoal::None;
2045 }
2046 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2047 }
2048
2049 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2050 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2051 let mut selections = self.selections::<Point>(cx);
2052 for selection in &mut selections {
2053 let head = selection.head().to_display_point(&display_map);
2054 let cursor = movement::right(&display_map, head)
2055 .unwrap()
2056 .to_point(&display_map);
2057 selection.set_head(cursor);
2058 selection.goal = SelectionGoal::None;
2059 }
2060 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2061 }
2062
2063 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2064 if matches!(self.mode, EditorMode::SingleLine) {
2065 cx.propagate_action();
2066 return;
2067 }
2068
2069 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2070 let mut selections = self.selections::<Point>(cx);
2071 for selection in &mut selections {
2072 let start = selection.start.to_display_point(&display_map);
2073 let end = selection.end.to_display_point(&display_map);
2074 if start != end {
2075 selection.goal = SelectionGoal::None;
2076 }
2077
2078 let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
2079 let cursor = start.to_point(&display_map);
2080 selection.start = cursor;
2081 selection.end = cursor;
2082 selection.goal = goal;
2083 selection.reversed = false;
2084 }
2085 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2086 }
2087
2088 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
2089 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2090 let mut selections = self.selections::<Point>(cx);
2091 for selection in &mut selections {
2092 let head = selection.head().to_display_point(&display_map);
2093 let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
2094 let cursor = head.to_point(&display_map);
2095 selection.set_head(cursor);
2096 selection.goal = goal;
2097 }
2098 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2099 }
2100
2101 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2102 if matches!(self.mode, EditorMode::SingleLine) {
2103 cx.propagate_action();
2104 return;
2105 }
2106
2107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2108 let mut selections = self.selections::<Point>(cx);
2109 for selection in &mut selections {
2110 let start = selection.start.to_display_point(&display_map);
2111 let end = selection.end.to_display_point(&display_map);
2112 if start != end {
2113 selection.goal = SelectionGoal::None;
2114 }
2115
2116 let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
2117 let cursor = start.to_point(&display_map);
2118 selection.start = cursor;
2119 selection.end = cursor;
2120 selection.goal = goal;
2121 selection.reversed = false;
2122 }
2123 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2124 }
2125
2126 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
2127 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2128 let mut selections = self.selections::<Point>(cx);
2129 for selection in &mut selections {
2130 let head = selection.head().to_display_point(&display_map);
2131 let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
2132 let cursor = head.to_point(&display_map);
2133 selection.set_head(cursor);
2134 selection.goal = goal;
2135 }
2136 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2137 }
2138
2139 pub fn move_to_previous_word_boundary(
2140 &mut self,
2141 _: &MoveToPreviousWordBoundary,
2142 cx: &mut ViewContext<Self>,
2143 ) {
2144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2145 let mut selections = self.selections::<Point>(cx);
2146 for selection in &mut selections {
2147 let head = selection.head().to_display_point(&display_map);
2148 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2149 selection.start = cursor.clone();
2150 selection.end = cursor;
2151 selection.reversed = false;
2152 selection.goal = SelectionGoal::None;
2153 }
2154 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2155 }
2156
2157 pub fn select_to_previous_word_boundary(
2158 &mut self,
2159 _: &SelectToPreviousWordBoundary,
2160 cx: &mut ViewContext<Self>,
2161 ) {
2162 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2163 let mut selections = self.selections::<Point>(cx);
2164 for selection in &mut selections {
2165 let head = selection.head().to_display_point(&display_map);
2166 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2167 selection.set_head(cursor);
2168 selection.goal = SelectionGoal::None;
2169 }
2170 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2171 }
2172
2173 pub fn delete_to_previous_word_boundary(
2174 &mut self,
2175 _: &DeleteToPreviousWordBoundary,
2176 cx: &mut ViewContext<Self>,
2177 ) {
2178 self.start_transaction(cx);
2179 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2180 let mut selections = self.selections::<Point>(cx);
2181 for selection in &mut selections {
2182 if selection.is_empty() {
2183 let head = selection.head().to_display_point(&display_map);
2184 let cursor =
2185 movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2186 selection.set_head(cursor);
2187 selection.goal = SelectionGoal::None;
2188 }
2189 }
2190 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2191 self.insert("", cx);
2192 self.end_transaction(cx);
2193 }
2194
2195 pub fn move_to_next_word_boundary(
2196 &mut self,
2197 _: &MoveToNextWordBoundary,
2198 cx: &mut ViewContext<Self>,
2199 ) {
2200 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2201 let mut selections = self.selections::<Point>(cx);
2202 for selection in &mut selections {
2203 let head = selection.head().to_display_point(&display_map);
2204 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2205 selection.start = cursor;
2206 selection.end = cursor;
2207 selection.reversed = false;
2208 selection.goal = SelectionGoal::None;
2209 }
2210 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2211 }
2212
2213 pub fn select_to_next_word_boundary(
2214 &mut self,
2215 _: &SelectToNextWordBoundary,
2216 cx: &mut ViewContext<Self>,
2217 ) {
2218 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2219 let mut selections = self.selections::<Point>(cx);
2220 for selection in &mut selections {
2221 let head = selection.head().to_display_point(&display_map);
2222 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2223 selection.set_head(cursor);
2224 selection.goal = SelectionGoal::None;
2225 }
2226 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2227 }
2228
2229 pub fn delete_to_next_word_boundary(
2230 &mut self,
2231 _: &DeleteToNextWordBoundary,
2232 cx: &mut ViewContext<Self>,
2233 ) {
2234 self.start_transaction(cx);
2235 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2236 let mut selections = self.selections::<Point>(cx);
2237 for selection in &mut selections {
2238 if selection.is_empty() {
2239 let head = selection.head().to_display_point(&display_map);
2240 let cursor =
2241 movement::next_word_boundary(&display_map, head).to_point(&display_map);
2242 selection.set_head(cursor);
2243 selection.goal = SelectionGoal::None;
2244 }
2245 }
2246 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2247 self.insert("", cx);
2248 self.end_transaction(cx);
2249 }
2250
2251 pub fn move_to_beginning_of_line(
2252 &mut self,
2253 _: &MoveToBeginningOfLine,
2254 cx: &mut ViewContext<Self>,
2255 ) {
2256 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2257 let mut selections = self.selections::<Point>(cx);
2258 for selection in &mut selections {
2259 let head = selection.head().to_display_point(&display_map);
2260 let new_head = movement::line_beginning(&display_map, head, true);
2261 let cursor = new_head.to_point(&display_map);
2262 selection.start = cursor;
2263 selection.end = cursor;
2264 selection.reversed = false;
2265 selection.goal = SelectionGoal::None;
2266 }
2267 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2268 }
2269
2270 pub fn select_to_beginning_of_line(
2271 &mut self,
2272 SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
2273 cx: &mut ViewContext<Self>,
2274 ) {
2275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2276 let mut selections = self.selections::<Point>(cx);
2277 for selection in &mut selections {
2278 let head = selection.head().to_display_point(&display_map);
2279 let new_head = movement::line_beginning(&display_map, head, *toggle_indent);
2280 selection.set_head(new_head.to_point(&display_map));
2281 selection.goal = SelectionGoal::None;
2282 }
2283 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2284 }
2285
2286 pub fn delete_to_beginning_of_line(
2287 &mut self,
2288 _: &DeleteToBeginningOfLine,
2289 cx: &mut ViewContext<Self>,
2290 ) {
2291 self.start_transaction(cx);
2292 self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
2293 self.backspace(&Backspace, cx);
2294 self.end_transaction(cx);
2295 }
2296
2297 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
2298 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2299 let mut selections = self.selections::<Point>(cx);
2300 {
2301 for selection in &mut selections {
2302 let head = selection.head().to_display_point(&display_map);
2303 let new_head = movement::line_end(&display_map, head);
2304 let anchor = new_head.to_point(&display_map);
2305 selection.start = anchor.clone();
2306 selection.end = anchor;
2307 selection.reversed = false;
2308 selection.goal = SelectionGoal::None;
2309 }
2310 }
2311 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2312 }
2313
2314 pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2315 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2316 let mut selections = self.selections::<Point>(cx);
2317 for selection in &mut selections {
2318 let head = selection.head().to_display_point(&display_map);
2319 let new_head = movement::line_end(&display_map, head);
2320 selection.set_head(new_head.to_point(&display_map));
2321 selection.goal = SelectionGoal::None;
2322 }
2323 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2324 }
2325
2326 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2327 self.start_transaction(cx);
2328 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2329 self.delete(&Delete, cx);
2330 self.end_transaction(cx);
2331 }
2332
2333 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2334 self.start_transaction(cx);
2335 self.select_to_end_of_line(&SelectToEndOfLine, cx);
2336 self.cut(&Cut, cx);
2337 self.end_transaction(cx);
2338 }
2339
2340 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2341 let selection = Selection {
2342 id: post_inc(&mut self.next_selection_id),
2343 start: 0,
2344 end: 0,
2345 reversed: false,
2346 goal: SelectionGoal::None,
2347 };
2348 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2349 }
2350
2351 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
2352 let mut selection = self.selections::<Point>(cx).last().unwrap().clone();
2353 selection.set_head(Point::zero());
2354 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2355 }
2356
2357 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
2358 let buffer = self.buffer.read(cx);
2359 let cursor = buffer.len();
2360 let selection = Selection {
2361 id: post_inc(&mut self.next_selection_id),
2362 start: cursor,
2363 end: cursor,
2364 reversed: false,
2365 goal: SelectionGoal::None,
2366 };
2367 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2368 }
2369
2370 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
2371 let mut selection = self.selections::<usize>(cx).last().unwrap().clone();
2372 selection.set_head(self.buffer.read(cx).len());
2373 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2374 }
2375
2376 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
2377 let selection = Selection {
2378 id: post_inc(&mut self.next_selection_id),
2379 start: 0,
2380 end: self.buffer.read(cx).len(),
2381 reversed: false,
2382 goal: SelectionGoal::None,
2383 };
2384 self.update_selections(vec![selection], None, cx);
2385 }
2386
2387 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
2388 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2389 let mut selections = self.selections::<Point>(cx);
2390 let buffer = self.buffer.read(cx);
2391 let max_point = buffer.max_point();
2392 for selection in &mut selections {
2393 let rows = selection.spanned_rows(true, &display_map).buffer_rows;
2394 selection.start = Point::new(rows.start, 0);
2395 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
2396 selection.reversed = false;
2397 }
2398 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2399 }
2400
2401 pub fn split_selection_into_lines(
2402 &mut self,
2403 _: &SplitSelectionIntoLines,
2404 cx: &mut ViewContext<Self>,
2405 ) {
2406 let selections = self.selections::<Point>(cx);
2407 let buffer = self.buffer.read(cx);
2408
2409 let mut to_unfold = Vec::new();
2410 let mut new_selections = Vec::new();
2411 for selection in selections.iter() {
2412 for row in selection.start.row..selection.end.row {
2413 let cursor = Point::new(row, buffer.line_len(row));
2414 new_selections.push(Selection {
2415 id: post_inc(&mut self.next_selection_id),
2416 start: cursor,
2417 end: cursor,
2418 reversed: false,
2419 goal: SelectionGoal::None,
2420 });
2421 }
2422 new_selections.push(Selection {
2423 id: selection.id,
2424 start: selection.end,
2425 end: selection.end,
2426 reversed: false,
2427 goal: SelectionGoal::None,
2428 });
2429 to_unfold.push(selection.start..selection.end);
2430 }
2431 self.unfold_ranges(to_unfold, cx);
2432 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2433 }
2434
2435 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2436 self.add_selection(true, cx);
2437 }
2438
2439 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2440 self.add_selection(false, cx);
2441 }
2442
2443 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2444 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2445 let mut selections = self.selections::<Point>(cx);
2446 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2447 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2448 let range = oldest_selection.display_range(&display_map).sorted();
2449 let columns = cmp::min(range.start.column(), range.end.column())
2450 ..cmp::max(range.start.column(), range.end.column());
2451
2452 selections.clear();
2453 let mut stack = Vec::new();
2454 for row in range.start.row()..=range.end.row() {
2455 if let Some(selection) = self.build_columnar_selection(
2456 &display_map,
2457 row,
2458 &columns,
2459 oldest_selection.reversed,
2460 ) {
2461 stack.push(selection.id);
2462 selections.push(selection);
2463 }
2464 }
2465
2466 if above {
2467 stack.reverse();
2468 }
2469
2470 AddSelectionsState { above, stack }
2471 });
2472
2473 let last_added_selection = *state.stack.last().unwrap();
2474 let mut new_selections = Vec::new();
2475 if above == state.above {
2476 let end_row = if above {
2477 0
2478 } else {
2479 display_map.max_point().row()
2480 };
2481
2482 'outer: for selection in selections {
2483 if selection.id == last_added_selection {
2484 let range = selection.display_range(&display_map).sorted();
2485 debug_assert_eq!(range.start.row(), range.end.row());
2486 let mut row = range.start.row();
2487 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2488 {
2489 start..end
2490 } else {
2491 cmp::min(range.start.column(), range.end.column())
2492 ..cmp::max(range.start.column(), range.end.column())
2493 };
2494
2495 while row != end_row {
2496 if above {
2497 row -= 1;
2498 } else {
2499 row += 1;
2500 }
2501
2502 if let Some(new_selection) = self.build_columnar_selection(
2503 &display_map,
2504 row,
2505 &columns,
2506 selection.reversed,
2507 ) {
2508 state.stack.push(new_selection.id);
2509 if above {
2510 new_selections.push(new_selection);
2511 new_selections.push(selection);
2512 } else {
2513 new_selections.push(selection);
2514 new_selections.push(new_selection);
2515 }
2516
2517 continue 'outer;
2518 }
2519 }
2520 }
2521
2522 new_selections.push(selection);
2523 }
2524 } else {
2525 new_selections = selections;
2526 new_selections.retain(|s| s.id != last_added_selection);
2527 state.stack.pop();
2528 }
2529
2530 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2531 if state.stack.len() > 1 {
2532 self.add_selections_state = Some(state);
2533 }
2534 }
2535
2536 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
2537 let replace_newest = action.0;
2538 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2539 let buffer = &display_map.buffer_snapshot;
2540 let mut selections = self.selections::<usize>(cx);
2541 if let Some(mut select_next_state) = self.select_next_state.take() {
2542 let query = &select_next_state.query;
2543 if !select_next_state.done {
2544 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
2545 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
2546 let mut next_selected_range = None;
2547
2548 let bytes_after_last_selection =
2549 buffer.bytes_in_range(last_selection.end..buffer.len());
2550 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
2551 let query_matches = query
2552 .stream_find_iter(bytes_after_last_selection)
2553 .map(|result| (last_selection.end, result))
2554 .chain(
2555 query
2556 .stream_find_iter(bytes_before_first_selection)
2557 .map(|result| (0, result)),
2558 );
2559 for (start_offset, query_match) in query_matches {
2560 let query_match = query_match.unwrap(); // can only fail due to I/O
2561 let offset_range =
2562 start_offset + query_match.start()..start_offset + query_match.end();
2563 let display_range = offset_range.start.to_display_point(&display_map)
2564 ..offset_range.end.to_display_point(&display_map);
2565
2566 if !select_next_state.wordwise
2567 || (!movement::is_inside_word(&display_map, display_range.start)
2568 && !movement::is_inside_word(&display_map, display_range.end))
2569 {
2570 next_selected_range = Some(offset_range);
2571 break;
2572 }
2573 }
2574
2575 if let Some(next_selected_range) = next_selected_range {
2576 if replace_newest {
2577 if let Some(newest_id) =
2578 selections.iter().max_by_key(|s| s.id).map(|s| s.id)
2579 {
2580 selections.retain(|s| s.id != newest_id);
2581 }
2582 }
2583 selections.push(Selection {
2584 id: post_inc(&mut self.next_selection_id),
2585 start: next_selected_range.start,
2586 end: next_selected_range.end,
2587 reversed: false,
2588 goal: SelectionGoal::None,
2589 });
2590 selections.sort_unstable_by_key(|s| s.start);
2591 self.update_selections(selections, Some(Autoscroll::Newest), cx);
2592 } else {
2593 select_next_state.done = true;
2594 }
2595 }
2596
2597 self.select_next_state = Some(select_next_state);
2598 } else if selections.len() == 1 {
2599 let selection = selections.last_mut().unwrap();
2600 if selection.start == selection.end {
2601 let word_range = movement::surrounding_word(
2602 &display_map,
2603 selection.start.to_display_point(&display_map),
2604 );
2605 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
2606 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
2607 selection.goal = SelectionGoal::None;
2608 selection.reversed = false;
2609
2610 let query = buffer
2611 .text_for_range(selection.start..selection.end)
2612 .collect::<String>();
2613 let select_state = SelectNextState {
2614 query: AhoCorasick::new_auto_configured(&[query]),
2615 wordwise: true,
2616 done: false,
2617 };
2618 self.update_selections(selections, Some(Autoscroll::Newest), cx);
2619 self.select_next_state = Some(select_state);
2620 } else {
2621 let query = buffer
2622 .text_for_range(selection.start..selection.end)
2623 .collect::<String>();
2624 self.select_next_state = Some(SelectNextState {
2625 query: AhoCorasick::new_auto_configured(&[query]),
2626 wordwise: false,
2627 done: false,
2628 });
2629 self.select_next(action, cx);
2630 }
2631 }
2632 }
2633
2634 pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
2635 // Get the line comment prefix. Split its trailing whitespace into a separate string,
2636 // as that portion won't be used for detecting if a line is a comment.
2637 let full_comment_prefix =
2638 if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
2639 prefix.to_string()
2640 } else {
2641 return;
2642 };
2643 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
2644 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
2645
2646 self.start_transaction(cx);
2647 let mut selections = self.selections::<Point>(cx);
2648 let mut all_selection_lines_are_comments = true;
2649 let mut edit_ranges = Vec::new();
2650 let mut last_toggled_row = None;
2651 self.buffer.update(cx, |buffer, cx| {
2652 let buffer_snapshot = buffer.snapshot(cx);
2653 for selection in &mut selections {
2654 edit_ranges.clear();
2655
2656 let end_row =
2657 if selection.end.row > selection.start.row && selection.end.column == 0 {
2658 selection.end.row
2659 } else {
2660 selection.end.row + 1
2661 };
2662
2663 for row in selection.start.row..end_row {
2664 // If multiple selections contain a given row, avoid processing that
2665 // row more than once.
2666 if last_toggled_row == Some(row) {
2667 continue;
2668 } else {
2669 last_toggled_row = Some(row);
2670 }
2671
2672 if buffer_snapshot.is_line_blank(row) {
2673 continue;
2674 }
2675
2676 let start = Point::new(row, buffer_snapshot.indent_column_for_line(row));
2677 let mut line_bytes = buffer_snapshot
2678 .bytes_in_range(start..buffer.max_point())
2679 .flatten()
2680 .copied();
2681
2682 // If this line currently begins with the line comment prefix, then record
2683 // the range containing the prefix.
2684 if all_selection_lines_are_comments
2685 && line_bytes
2686 .by_ref()
2687 .take(comment_prefix.len())
2688 .eq(comment_prefix.bytes())
2689 {
2690 // Include any whitespace that matches the comment prefix.
2691 let matching_whitespace_len = line_bytes
2692 .zip(comment_prefix_whitespace.bytes())
2693 .take_while(|(a, b)| a == b)
2694 .count() as u32;
2695 let end = Point::new(
2696 row,
2697 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
2698 );
2699 edit_ranges.push(start..end);
2700 }
2701 // If this line does not begin with the line comment prefix, then record
2702 // the position where the prefix should be inserted.
2703 else {
2704 all_selection_lines_are_comments = false;
2705 edit_ranges.push(start..start);
2706 }
2707 }
2708
2709 if !edit_ranges.is_empty() {
2710 if all_selection_lines_are_comments {
2711 buffer.edit(edit_ranges.iter().cloned(), "", cx);
2712 } else {
2713 let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
2714 let edit_ranges = edit_ranges.iter().map(|range| {
2715 let position = Point::new(range.start.row, min_column);
2716 position..position
2717 });
2718 buffer.edit(edit_ranges, &full_comment_prefix, cx);
2719 }
2720 }
2721 }
2722 });
2723
2724 self.update_selections(self.selections::<usize>(cx), Some(Autoscroll::Fit), cx);
2725 self.end_transaction(cx);
2726 }
2727
2728 pub fn select_larger_syntax_node(
2729 &mut self,
2730 _: &SelectLargerSyntaxNode,
2731 cx: &mut ViewContext<Self>,
2732 ) {
2733 let old_selections = self.selections::<usize>(cx).into_boxed_slice();
2734 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2735 let buffer = self.buffer.read(cx).snapshot(cx);
2736
2737 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2738 let mut selected_larger_node = false;
2739 let mut new_selections = old_selections
2740 .iter()
2741 .map(|selection| {
2742 let old_range = selection.start..selection.end;
2743 let mut new_range = old_range.clone();
2744 while let Some(containing_range) =
2745 buffer.range_for_syntax_ancestor(new_range.clone())
2746 {
2747 new_range = containing_range;
2748 if !display_map.intersects_fold(new_range.start)
2749 && !display_map.intersects_fold(new_range.end)
2750 {
2751 break;
2752 }
2753 }
2754
2755 selected_larger_node |= new_range != old_range;
2756 Selection {
2757 id: selection.id,
2758 start: new_range.start,
2759 end: new_range.end,
2760 goal: SelectionGoal::None,
2761 reversed: selection.reversed,
2762 }
2763 })
2764 .collect::<Vec<_>>();
2765
2766 if selected_larger_node {
2767 stack.push(old_selections);
2768 new_selections.sort_unstable_by_key(|selection| selection.start);
2769 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2770 }
2771 self.select_larger_syntax_node_stack = stack;
2772 }
2773
2774 pub fn select_smaller_syntax_node(
2775 &mut self,
2776 _: &SelectSmallerSyntaxNode,
2777 cx: &mut ViewContext<Self>,
2778 ) {
2779 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2780 if let Some(selections) = stack.pop() {
2781 self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
2782 }
2783 self.select_larger_syntax_node_stack = stack;
2784 }
2785
2786 pub fn move_to_enclosing_bracket(
2787 &mut self,
2788 _: &MoveToEnclosingBracket,
2789 cx: &mut ViewContext<Self>,
2790 ) {
2791 let mut selections = self.selections::<usize>(cx);
2792 let buffer = self.buffer.read(cx).snapshot(cx);
2793 for selection in &mut selections {
2794 if let Some((open_range, close_range)) =
2795 buffer.enclosing_bracket_ranges(selection.start..selection.end)
2796 {
2797 let close_range = close_range.to_inclusive();
2798 let destination = if close_range.contains(&selection.start)
2799 && close_range.contains(&selection.end)
2800 {
2801 open_range.end
2802 } else {
2803 *close_range.start()
2804 };
2805 selection.start = destination;
2806 selection.end = destination;
2807 }
2808 }
2809
2810 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2811 }
2812
2813 pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
2814 let buffer = self.buffer.read(cx).snapshot(cx);
2815 let selection = self.newest_selection::<usize>(cx);
2816 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
2817 active_diagnostics
2818 .primary_range
2819 .to_offset(&buffer)
2820 .to_inclusive()
2821 });
2822 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
2823 if active_primary_range.contains(&selection.head()) {
2824 *active_primary_range.end()
2825 } else {
2826 selection.head()
2827 }
2828 } else {
2829 selection.head()
2830 };
2831
2832 loop {
2833 let next_group = buffer
2834 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
2835 .find_map(|(range, diagnostic)| {
2836 if diagnostic.is_primary
2837 && !range.is_empty()
2838 && Some(range.end) != active_primary_range.as_ref().map(|r| *r.end())
2839 {
2840 Some((range, diagnostic.group_id))
2841 } else {
2842 None
2843 }
2844 });
2845
2846 if let Some((primary_range, group_id)) = next_group {
2847 self.activate_diagnostics(group_id, cx);
2848 self.update_selections(
2849 vec![Selection {
2850 id: selection.id,
2851 start: primary_range.start,
2852 end: primary_range.start,
2853 reversed: false,
2854 goal: SelectionGoal::None,
2855 }],
2856 Some(Autoscroll::Center),
2857 cx,
2858 );
2859 break;
2860 } else if search_start == 0 {
2861 break;
2862 } else {
2863 // Cycle around to the start of the buffer.
2864 search_start = 0;
2865 }
2866 }
2867 }
2868
2869 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
2870 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
2871 let buffer = self.buffer.read(cx).snapshot(cx);
2872 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
2873 let is_valid = buffer
2874 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
2875 .any(|(range, diagnostic)| {
2876 diagnostic.is_primary
2877 && !range.is_empty()
2878 && range.start == primary_range_start
2879 && diagnostic.message == active_diagnostics.primary_message
2880 });
2881
2882 if is_valid != active_diagnostics.is_valid {
2883 active_diagnostics.is_valid = is_valid;
2884 let mut new_styles = HashMap::new();
2885 for (block_id, diagnostic) in &active_diagnostics.blocks {
2886 let build_settings = self.build_settings.clone();
2887 let diagnostic = diagnostic.clone();
2888 new_styles.insert(*block_id, move |cx: &BlockContext| {
2889 let diagnostic = diagnostic.clone();
2890 let settings = build_settings.borrow()(cx.cx);
2891 render_diagnostic(diagnostic, &settings.style, is_valid, cx.anchor_x)
2892 });
2893 }
2894 self.display_map
2895 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
2896 }
2897 }
2898 }
2899
2900 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
2901 self.dismiss_diagnostics(cx);
2902 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
2903 let buffer = self.buffer.read(cx).snapshot(cx);
2904
2905 let mut primary_range = None;
2906 let mut primary_message = None;
2907 let mut group_end = Point::zero();
2908 let diagnostic_group = buffer
2909 .diagnostic_group::<Point>(group_id)
2910 .map(|(range, diagnostic)| {
2911 if range.end > group_end {
2912 group_end = range.end;
2913 }
2914 if diagnostic.is_primary {
2915 primary_range = Some(range.clone());
2916 primary_message = Some(diagnostic.message.clone());
2917 }
2918 (range, diagnostic.clone())
2919 })
2920 .collect::<Vec<_>>();
2921 let primary_range = primary_range.unwrap();
2922 let primary_message = primary_message.unwrap();
2923 let primary_range =
2924 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
2925
2926 let blocks = display_map
2927 .insert_blocks(
2928 diagnostic_group.iter().map(|(range, diagnostic)| {
2929 let build_settings = self.build_settings.clone();
2930 let diagnostic = diagnostic.clone();
2931 let message_height = diagnostic.message.lines().count() as u8;
2932
2933 BlockProperties {
2934 position: range.start,
2935 height: message_height,
2936 render: Arc::new(move |cx| {
2937 let settings = build_settings.borrow()(cx.cx);
2938 let diagnostic = diagnostic.clone();
2939 render_diagnostic(diagnostic, &settings.style, true, cx.anchor_x)
2940 }),
2941 disposition: BlockDisposition::Below,
2942 }
2943 }),
2944 cx,
2945 )
2946 .into_iter()
2947 .zip(
2948 diagnostic_group
2949 .into_iter()
2950 .map(|(_, diagnostic)| diagnostic),
2951 )
2952 .collect();
2953
2954 Some(ActiveDiagnosticGroup {
2955 primary_range,
2956 primary_message,
2957 blocks,
2958 is_valid: true,
2959 })
2960 });
2961 }
2962
2963 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
2964 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
2965 self.display_map.update(cx, |display_map, cx| {
2966 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
2967 });
2968 cx.notify();
2969 }
2970 }
2971
2972 fn build_columnar_selection(
2973 &mut self,
2974 display_map: &DisplaySnapshot,
2975 row: u32,
2976 columns: &Range<u32>,
2977 reversed: bool,
2978 ) -> Option<Selection<Point>> {
2979 let is_empty = columns.start == columns.end;
2980 let line_len = display_map.line_len(row);
2981 if columns.start < line_len || (is_empty && columns.start == line_len) {
2982 let start = DisplayPoint::new(row, columns.start);
2983 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
2984 Some(Selection {
2985 id: post_inc(&mut self.next_selection_id),
2986 start: start.to_point(display_map),
2987 end: end.to_point(display_map),
2988 reversed,
2989 goal: SelectionGoal::ColumnRange {
2990 start: columns.start,
2991 end: columns.end,
2992 },
2993 })
2994 } else {
2995 None
2996 }
2997 }
2998
2999 pub fn active_selection_sets<'a>(
3000 &'a self,
3001 cx: &'a AppContext,
3002 ) -> impl 'a + Iterator<Item = SelectionSetId> {
3003 let buffer = self.buffer.read(cx);
3004 let replica_id = buffer.replica_id();
3005 buffer
3006 .selection_sets()
3007 .filter(move |(set_id, set)| {
3008 set.active && (set_id.replica_id != replica_id || **set_id == self.selection_set_id)
3009 })
3010 .map(|(set_id, _)| *set_id)
3011 }
3012
3013 pub fn intersecting_selections<'a>(
3014 &'a self,
3015 set_id: SelectionSetId,
3016 range: Range<DisplayPoint>,
3017 cx: &'a mut MutableAppContext,
3018 ) -> Vec<Selection<DisplayPoint>> {
3019 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3020 let buffer = self.buffer.read(cx);
3021
3022 let pending_selection = if set_id == self.selection_set_id {
3023 self.pending_selection.as_ref().and_then(|pending| {
3024 let selection_start = pending.selection.start.to_display_point(&display_map);
3025 let selection_end = pending.selection.end.to_display_point(&display_map);
3026 if selection_start <= range.end || selection_end <= range.end {
3027 Some(Selection {
3028 id: pending.selection.id,
3029 start: selection_start,
3030 end: selection_end,
3031 reversed: pending.selection.reversed,
3032 goal: pending.selection.goal,
3033 })
3034 } else {
3035 None
3036 }
3037 })
3038 } else {
3039 None
3040 };
3041
3042 let range = (range.start.to_offset(&display_map, Bias::Left), Bias::Left)
3043 ..(range.end.to_offset(&display_map, Bias::Left), Bias::Right);
3044 buffer
3045 .selection_set(set_id)
3046 .unwrap()
3047 .intersecting_selections::<Point, _>(range, &buffer.as_snapshot())
3048 .map(move |s| Selection {
3049 id: s.id,
3050 start: s.start.to_display_point(&display_map),
3051 end: s.end.to_display_point(&display_map),
3052 reversed: s.reversed,
3053 goal: s.goal,
3054 })
3055 .chain(pending_selection)
3056 .collect()
3057 }
3058
3059 pub fn selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3060 where
3061 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3062 {
3063 let buffer = self.buffer.read(cx).snapshot(cx);
3064 let mut selections = self.selection_set(cx).selections::<D>(&buffer).peekable();
3065 let mut pending_selection = self.pending_selection(cx);
3066
3067 iter::from_fn(move || {
3068 if let Some(pending) = pending_selection.as_mut() {
3069 while let Some(next_selection) = selections.peek() {
3070 if pending.start <= next_selection.end && pending.end >= next_selection.start {
3071 let next_selection = selections.next().unwrap();
3072 if next_selection.start < pending.start {
3073 pending.start = next_selection.start;
3074 }
3075 if next_selection.end > pending.end {
3076 pending.end = next_selection.end;
3077 }
3078 } else if next_selection.end < pending.start {
3079 return selections.next();
3080 } else {
3081 break;
3082 }
3083 }
3084
3085 pending_selection.take()
3086 } else {
3087 selections.next()
3088 }
3089 })
3090 .collect()
3091 }
3092
3093 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3094 &self,
3095 cx: &AppContext,
3096 ) -> Option<Selection<D>> {
3097 let buffer = self.buffer.read(cx).as_snapshot();
3098 self.pending_selection.as_ref().map(|pending| Selection {
3099 id: pending.selection.id,
3100 start: pending.selection.start.summary::<D>(&buffer),
3101 end: pending.selection.end.summary::<D>(&buffer),
3102 reversed: pending.selection.reversed,
3103 goal: pending.selection.goal,
3104 })
3105 }
3106
3107 fn selection_count<'a>(&self, cx: &'a AppContext) -> usize {
3108 let mut selection_count = self.selection_set(cx).len();
3109 if self.pending_selection.is_some() {
3110 selection_count += 1;
3111 }
3112 selection_count
3113 }
3114
3115 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3116 &self,
3117 snapshot: &MultiBufferSnapshot,
3118 cx: &AppContext,
3119 ) -> Selection<D> {
3120 self.selection_set(cx)
3121 .oldest_selection(snapshot)
3122 .or_else(|| self.pending_selection(cx))
3123 .unwrap()
3124 }
3125
3126 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3127 &self,
3128 cx: &AppContext,
3129 ) -> Selection<D> {
3130 self.pending_selection(cx)
3131 .or_else(|| {
3132 self.selection_set(cx)
3133 .newest_selection(&self.buffer.read(cx).as_snapshot())
3134 })
3135 .unwrap()
3136 }
3137
3138 fn selection_set<'a>(&self, cx: &'a AppContext) -> &'a SelectionSet {
3139 self.buffer
3140 .read(cx)
3141 .selection_set(self.selection_set_id)
3142 .unwrap()
3143 }
3144
3145 pub fn update_selections<T>(
3146 &mut self,
3147 mut selections: Vec<Selection<T>>,
3148 autoscroll: Option<Autoscroll>,
3149 cx: &mut ViewContext<Self>,
3150 ) where
3151 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3152 {
3153 // Merge overlapping selections.
3154 let buffer = self.buffer.read(cx).snapshot(cx);
3155 let mut i = 1;
3156 while i < selections.len() {
3157 if selections[i - 1].end >= selections[i].start {
3158 let removed = selections.remove(i);
3159 if removed.start < selections[i - 1].start {
3160 selections[i - 1].start = removed.start;
3161 }
3162 if removed.end > selections[i - 1].end {
3163 selections[i - 1].end = removed.end;
3164 }
3165 } else {
3166 i += 1;
3167 }
3168 }
3169
3170 self.pending_selection = None;
3171 self.add_selections_state = None;
3172 self.select_next_state = None;
3173 self.select_larger_syntax_node_stack.clear();
3174 while let Some(autoclose_pair_state) = self.autoclose_stack.last() {
3175 let all_selections_inside_autoclose_ranges =
3176 if selections.len() == autoclose_pair_state.ranges.len() {
3177 selections
3178 .iter()
3179 .zip(autoclose_pair_state.ranges.ranges::<Point>(&buffer))
3180 .all(|(selection, autoclose_range)| {
3181 let head = selection.head().to_point(&buffer);
3182 autoclose_range.start <= head && autoclose_range.end >= head
3183 })
3184 } else {
3185 false
3186 };
3187
3188 if all_selections_inside_autoclose_ranges {
3189 break;
3190 } else {
3191 self.autoclose_stack.pop();
3192 }
3193 }
3194
3195 if let Some(autoscroll) = autoscroll {
3196 self.request_autoscroll(autoscroll, cx);
3197 }
3198 self.pause_cursor_blinking(cx);
3199
3200 self.buffer.update(cx, |buffer, cx| {
3201 buffer
3202 .update_selection_set(self.selection_set_id, &selections, cx)
3203 .unwrap();
3204 });
3205 }
3206
3207 fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3208 self.autoscroll_request = Some(autoscroll);
3209 cx.notify();
3210 }
3211
3212 fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3213 self.end_selection(cx);
3214 self.buffer.update(cx, |buffer, _| {
3215 buffer
3216 .start_transaction(Some(self.selection_set_id))
3217 .unwrap()
3218 });
3219 }
3220
3221 fn end_transaction(&self, cx: &mut ViewContext<Self>) {
3222 self.buffer.update(cx, |buffer, cx| {
3223 buffer
3224 .end_transaction(Some(self.selection_set_id), cx)
3225 .unwrap()
3226 });
3227 }
3228
3229 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3230 log::info!("Editor::page_up");
3231 }
3232
3233 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3234 log::info!("Editor::page_down");
3235 }
3236
3237 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3238 let mut fold_ranges = Vec::new();
3239
3240 let selections = self.selections::<Point>(cx);
3241 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3242 for selection in selections {
3243 let range = selection.display_range(&display_map).sorted();
3244 let buffer_start_row = range.start.to_point(&display_map).row;
3245
3246 for row in (0..=range.end.row()).rev() {
3247 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3248 let fold_range = self.foldable_range_for_line(&display_map, row);
3249 if fold_range.end.row >= buffer_start_row {
3250 fold_ranges.push(fold_range);
3251 if row <= range.start.row() {
3252 break;
3253 }
3254 }
3255 }
3256 }
3257 }
3258
3259 self.fold_ranges(fold_ranges, cx);
3260 }
3261
3262 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3263 let selections = self.selections::<Point>(cx);
3264 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3265 let buffer = self.buffer.read(cx);
3266 let ranges = selections
3267 .iter()
3268 .map(|s| {
3269 let range = s.display_range(&display_map).sorted();
3270 let mut start = range.start.to_point(&display_map);
3271 let mut end = range.end.to_point(&display_map);
3272 start.column = 0;
3273 end.column = buffer.line_len(end.row);
3274 start..end
3275 })
3276 .collect::<Vec<_>>();
3277 self.unfold_ranges(ranges, cx);
3278 }
3279
3280 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
3281 let max_point = display_map.max_point();
3282 if display_row >= max_point.row() {
3283 false
3284 } else {
3285 let (start_indent, is_blank) = display_map.line_indent(display_row);
3286 if is_blank {
3287 false
3288 } else {
3289 for display_row in display_row + 1..=max_point.row() {
3290 let (indent, is_blank) = display_map.line_indent(display_row);
3291 if !is_blank {
3292 return indent > start_indent;
3293 }
3294 }
3295 false
3296 }
3297 }
3298 }
3299
3300 fn foldable_range_for_line(
3301 &self,
3302 display_map: &DisplaySnapshot,
3303 start_row: u32,
3304 ) -> Range<Point> {
3305 let max_point = display_map.max_point();
3306
3307 let (start_indent, _) = display_map.line_indent(start_row);
3308 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3309 let mut end = None;
3310 for row in start_row + 1..=max_point.row() {
3311 let (indent, is_blank) = display_map.line_indent(row);
3312 if !is_blank && indent <= start_indent {
3313 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3314 break;
3315 }
3316 }
3317
3318 let end = end.unwrap_or(max_point);
3319 return start.to_point(display_map)..end.to_point(display_map);
3320 }
3321
3322 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3323 let selections = self.selections::<Point>(cx);
3324 let ranges = selections.into_iter().map(|s| s.start..s.end);
3325 self.fold_ranges(ranges, cx);
3326 }
3327
3328 fn fold_ranges<T: ToOffset>(
3329 &mut self,
3330 ranges: impl IntoIterator<Item = Range<T>>,
3331 cx: &mut ViewContext<Self>,
3332 ) {
3333 let mut ranges = ranges.into_iter().peekable();
3334 if ranges.peek().is_some() {
3335 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3336 self.request_autoscroll(Autoscroll::Fit, cx);
3337 cx.notify();
3338 }
3339 }
3340
3341 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3342 if !ranges.is_empty() {
3343 self.display_map
3344 .update(cx, |map, cx| map.unfold(ranges, cx));
3345 self.request_autoscroll(Autoscroll::Fit, cx);
3346 cx.notify();
3347 }
3348 }
3349
3350 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3351 self.display_map
3352 .update(cx, |map, cx| map.snapshot(cx))
3353 .longest_row()
3354 }
3355
3356 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3357 self.display_map
3358 .update(cx, |map, cx| map.snapshot(cx))
3359 .max_point()
3360 }
3361
3362 pub fn text(&self, cx: &AppContext) -> String {
3363 self.buffer.read(cx).text()
3364 }
3365
3366 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3367 self.display_map
3368 .update(cx, |map, cx| map.snapshot(cx))
3369 .text()
3370 }
3371
3372 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
3373 self.display_map
3374 .update(cx, |map, cx| map.set_wrap_width(width, cx))
3375 }
3376
3377 pub fn set_highlighted_row(&mut self, row: Option<u32>) {
3378 self.highlighted_row = row;
3379 }
3380
3381 pub fn highlighted_row(&mut self) -> Option<u32> {
3382 self.highlighted_row
3383 }
3384
3385 fn next_blink_epoch(&mut self) -> usize {
3386 self.blink_epoch += 1;
3387 self.blink_epoch
3388 }
3389
3390 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3391 self.show_local_cursors = true;
3392 cx.notify();
3393
3394 let epoch = self.next_blink_epoch();
3395 cx.spawn(|this, mut cx| {
3396 let this = this.downgrade();
3397 async move {
3398 Timer::after(CURSOR_BLINK_INTERVAL).await;
3399 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3400 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3401 }
3402 }
3403 })
3404 .detach();
3405 }
3406
3407 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3408 if epoch == self.blink_epoch {
3409 self.blinking_paused = false;
3410 self.blink_cursors(epoch, cx);
3411 }
3412 }
3413
3414 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3415 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3416 self.show_local_cursors = !self.show_local_cursors;
3417 cx.notify();
3418
3419 let epoch = self.next_blink_epoch();
3420 cx.spawn(|this, mut cx| {
3421 let this = this.downgrade();
3422 async move {
3423 Timer::after(CURSOR_BLINK_INTERVAL).await;
3424 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3425 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3426 }
3427 }
3428 })
3429 .detach();
3430 }
3431 }
3432
3433 pub fn show_local_cursors(&self) -> bool {
3434 self.show_local_cursors
3435 }
3436
3437 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
3438 self.refresh_active_diagnostics(cx);
3439 cx.notify();
3440 }
3441
3442 fn on_buffer_event(
3443 &mut self,
3444 _: ModelHandle<MultiBuffer>,
3445 event: &language::Event,
3446 cx: &mut ViewContext<Self>,
3447 ) {
3448 match event {
3449 language::Event::Edited => cx.emit(Event::Edited),
3450 language::Event::Dirtied => cx.emit(Event::Dirtied),
3451 language::Event::Saved => cx.emit(Event::Saved),
3452 language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
3453 language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
3454 language::Event::Closed => cx.emit(Event::Closed),
3455 _ => {}
3456 }
3457 }
3458
3459 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3460 cx.notify();
3461 }
3462}
3463
3464impl EditorSnapshot {
3465 pub fn is_focused(&self) -> bool {
3466 self.is_focused
3467 }
3468
3469 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3470 self.placeholder_text.as_ref()
3471 }
3472
3473 pub fn scroll_position(&self) -> Vector2F {
3474 compute_scroll_position(
3475 &self.display_snapshot,
3476 self.scroll_position,
3477 &self.scroll_top_anchor,
3478 )
3479 }
3480}
3481
3482impl Deref for EditorSnapshot {
3483 type Target = DisplaySnapshot;
3484
3485 fn deref(&self) -> &Self::Target {
3486 &self.display_snapshot
3487 }
3488}
3489
3490impl EditorSettings {
3491 #[cfg(any(test, feature = "test-support"))]
3492 pub fn test(cx: &AppContext) -> Self {
3493 Self {
3494 tab_size: 4,
3495 soft_wrap: SoftWrap::None,
3496 style: {
3497 let font_cache: &gpui::FontCache = cx.font_cache();
3498 let font_family_name = Arc::from("Monaco");
3499 let font_properties = Default::default();
3500 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3501 let font_id = font_cache
3502 .select_font(font_family_id, &font_properties)
3503 .unwrap();
3504 EditorStyle {
3505 text: gpui::fonts::TextStyle {
3506 font_family_name,
3507 font_family_id,
3508 font_id,
3509 font_size: 14.,
3510 color: gpui::color::Color::from_u32(0xff0000ff),
3511 font_properties,
3512 underline: None,
3513 },
3514 placeholder_text: None,
3515 background: Default::default(),
3516 gutter_background: Default::default(),
3517 active_line_background: Default::default(),
3518 highlighted_line_background: Default::default(),
3519 line_number: Default::default(),
3520 line_number_active: Default::default(),
3521 selection: Default::default(),
3522 guest_selections: Default::default(),
3523 syntax: Default::default(),
3524 error_diagnostic: Default::default(),
3525 invalid_error_diagnostic: Default::default(),
3526 warning_diagnostic: Default::default(),
3527 invalid_warning_diagnostic: Default::default(),
3528 information_diagnostic: Default::default(),
3529 invalid_information_diagnostic: Default::default(),
3530 hint_diagnostic: Default::default(),
3531 invalid_hint_diagnostic: Default::default(),
3532 }
3533 },
3534 }
3535 }
3536}
3537
3538fn compute_scroll_position(
3539 snapshot: &DisplaySnapshot,
3540 mut scroll_position: Vector2F,
3541 scroll_top_anchor: &Anchor,
3542) -> Vector2F {
3543 let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3544 scroll_position.set_y(scroll_top + scroll_position.y());
3545 scroll_position
3546}
3547
3548pub enum Event {
3549 Activate,
3550 Edited,
3551 Blurred,
3552 Dirtied,
3553 Saved,
3554 FileHandleChanged,
3555 Closed,
3556}
3557
3558impl Entity for Editor {
3559 type Event = Event;
3560
3561 fn release(&mut self, cx: &mut MutableAppContext) {
3562 self.buffer.update(cx, |buffer, cx| {
3563 buffer
3564 .remove_selection_set(self.selection_set_id, cx)
3565 .unwrap();
3566 });
3567 }
3568}
3569
3570impl View for Editor {
3571 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3572 let settings = self.build_settings.borrow_mut()(cx);
3573 self.display_map.update(cx, |map, cx| {
3574 map.set_font(
3575 settings.style.text.font_id,
3576 settings.style.text.font_size,
3577 cx,
3578 )
3579 });
3580 EditorElement::new(self.handle.clone(), settings).boxed()
3581 }
3582
3583 fn ui_name() -> &'static str {
3584 "Editor"
3585 }
3586
3587 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3588 self.focused = true;
3589 self.blink_cursors(self.blink_epoch, cx);
3590 self.buffer.update(cx, |buffer, cx| {
3591 buffer
3592 .set_active_selection_set(Some(self.selection_set_id), cx)
3593 .unwrap();
3594 });
3595 }
3596
3597 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3598 self.focused = false;
3599 self.show_local_cursors = false;
3600 self.buffer.update(cx, |buffer, cx| {
3601 buffer.set_active_selection_set(None, cx).unwrap();
3602 });
3603 cx.emit(Event::Blurred);
3604 cx.notify();
3605 }
3606
3607 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3608 let mut cx = Self::default_keymap_context();
3609 let mode = match self.mode {
3610 EditorMode::SingleLine => "single_line",
3611 EditorMode::AutoHeight { .. } => "auto_height",
3612 EditorMode::Full => "full",
3613 };
3614 cx.map.insert("mode".into(), mode.into());
3615 cx
3616 }
3617}
3618
3619impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3620 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3621 let start = self.start.to_point(buffer);
3622 let end = self.end.to_point(buffer);
3623 if self.reversed {
3624 end..start
3625 } else {
3626 start..end
3627 }
3628 }
3629
3630 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3631 let start = self.start.to_offset(buffer);
3632 let end = self.end.to_offset(buffer);
3633 if self.reversed {
3634 end..start
3635 } else {
3636 start..end
3637 }
3638 }
3639
3640 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
3641 let start = self
3642 .start
3643 .to_point(&map.buffer_snapshot)
3644 .to_display_point(map);
3645 let end = self
3646 .end
3647 .to_point(&map.buffer_snapshot)
3648 .to_display_point(map);
3649 if self.reversed {
3650 end..start
3651 } else {
3652 start..end
3653 }
3654 }
3655
3656 fn spanned_rows(
3657 &self,
3658 include_end_if_at_line_start: bool,
3659 map: &DisplaySnapshot,
3660 ) -> SpannedRows {
3661 let display_start = self
3662 .start
3663 .to_point(&map.buffer_snapshot)
3664 .to_display_point(map);
3665 let mut display_end = self
3666 .end
3667 .to_point(&map.buffer_snapshot)
3668 .to_display_point(map);
3669 if !include_end_if_at_line_start
3670 && display_end.row() != map.max_point().row()
3671 && display_start.row() != display_end.row()
3672 && display_end.column() == 0
3673 {
3674 *display_end.row_mut() -= 1;
3675 }
3676
3677 let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3678 let (display_end, buffer_end) = map.next_row_boundary(display_end);
3679
3680 SpannedRows {
3681 buffer_rows: buffer_start.row..buffer_end.row + 1,
3682 display_rows: display_start.row()..display_end.row() + 1,
3683 }
3684 }
3685}
3686
3687fn render_diagnostic(
3688 diagnostic: Diagnostic,
3689 style: &EditorStyle,
3690 valid: bool,
3691 anchor_x: f32,
3692) -> ElementBox {
3693 let mut text_style = style.text.clone();
3694 text_style.color = diagnostic_style(diagnostic.severity, valid, &style).text;
3695 Text::new(diagnostic.message, text_style)
3696 .contained()
3697 .with_margin_left(anchor_x)
3698 .boxed()
3699}
3700
3701pub fn diagnostic_style(
3702 severity: DiagnosticSeverity,
3703 valid: bool,
3704 style: &EditorStyle,
3705) -> DiagnosticStyle {
3706 match (severity, valid) {
3707 (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3708 (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3709 (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3710 (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3711 (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3712 (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3713 (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3714 (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3715 _ => Default::default(),
3716 }
3717}
3718
3719#[cfg(test)]
3720mod tests {
3721 use super::*;
3722 use language::LanguageConfig;
3723 use text::Point;
3724 use unindent::Unindent;
3725 use util::test::sample_text;
3726
3727 #[gpui::test]
3728 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3729 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3730 let settings = EditorSettings::test(cx);
3731 let (_, editor) =
3732 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3733
3734 editor.update(cx, |view, cx| {
3735 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3736 });
3737
3738 assert_eq!(
3739 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3740 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3741 );
3742
3743 editor.update(cx, |view, cx| {
3744 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3745 });
3746
3747 assert_eq!(
3748 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3749 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3750 );
3751
3752 editor.update(cx, |view, cx| {
3753 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3754 });
3755
3756 assert_eq!(
3757 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3758 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3759 );
3760
3761 editor.update(cx, |view, cx| {
3762 view.end_selection(cx);
3763 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3764 });
3765
3766 assert_eq!(
3767 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3768 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3769 );
3770
3771 editor.update(cx, |view, cx| {
3772 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
3773 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
3774 });
3775
3776 assert_eq!(
3777 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3778 [
3779 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3780 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3781 ]
3782 );
3783
3784 editor.update(cx, |view, cx| {
3785 view.end_selection(cx);
3786 });
3787
3788 assert_eq!(
3789 editor.update(cx, |view, cx| view.selection_ranges(cx)),
3790 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3791 );
3792 }
3793
3794 #[gpui::test]
3795 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3796 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3797 let settings = EditorSettings::test(cx);
3798 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3799
3800 view.update(cx, |view, cx| {
3801 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3802 assert_eq!(
3803 view.selection_ranges(cx),
3804 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3805 );
3806 });
3807
3808 view.update(cx, |view, cx| {
3809 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3810 assert_eq!(
3811 view.selection_ranges(cx),
3812 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3813 );
3814 });
3815
3816 view.update(cx, |view, cx| {
3817 view.cancel(&Cancel, cx);
3818 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3819 assert_eq!(
3820 view.selection_ranges(cx),
3821 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3822 );
3823 });
3824 }
3825
3826 #[gpui::test]
3827 fn test_cancel(cx: &mut gpui::MutableAppContext) {
3828 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3829 let settings = EditorSettings::test(cx);
3830 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3831
3832 view.update(cx, |view, cx| {
3833 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
3834 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3835 view.end_selection(cx);
3836
3837 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
3838 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
3839 view.end_selection(cx);
3840 assert_eq!(
3841 view.selection_ranges(cx),
3842 [
3843 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
3844 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
3845 ]
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(3, 4)..DisplayPoint::new(1, 1)]
3854 );
3855 });
3856
3857 view.update(cx, |view, cx| {
3858 view.cancel(&Cancel, cx);
3859 assert_eq!(
3860 view.selection_ranges(cx),
3861 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
3862 );
3863 });
3864 }
3865
3866 #[gpui::test]
3867 fn test_fold(cx: &mut gpui::MutableAppContext) {
3868 let buffer = MultiBuffer::build_simple(
3869 &"
3870 impl Foo {
3871 // Hello!
3872
3873 fn a() {
3874 1
3875 }
3876
3877 fn b() {
3878 2
3879 }
3880
3881 fn c() {
3882 3
3883 }
3884 }
3885 "
3886 .unindent(),
3887 cx,
3888 );
3889 let settings = EditorSettings::test(&cx);
3890 let (_, view) = cx.add_window(Default::default(), |cx| {
3891 build_editor(buffer.clone(), settings, cx)
3892 });
3893
3894 view.update(cx, |view, cx| {
3895 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
3896 .unwrap();
3897 view.fold(&Fold, cx);
3898 assert_eq!(
3899 view.display_text(cx),
3900 "
3901 impl Foo {
3902 // Hello!
3903
3904 fn a() {
3905 1
3906 }
3907
3908 fn b() {…
3909 }
3910
3911 fn c() {…
3912 }
3913 }
3914 "
3915 .unindent(),
3916 );
3917
3918 view.fold(&Fold, cx);
3919 assert_eq!(
3920 view.display_text(cx),
3921 "
3922 impl Foo {…
3923 }
3924 "
3925 .unindent(),
3926 );
3927
3928 view.unfold(&Unfold, cx);
3929 assert_eq!(
3930 view.display_text(cx),
3931 "
3932 impl Foo {
3933 // Hello!
3934
3935 fn a() {
3936 1
3937 }
3938
3939 fn b() {…
3940 }
3941
3942 fn c() {…
3943 }
3944 }
3945 "
3946 .unindent(),
3947 );
3948
3949 view.unfold(&Unfold, cx);
3950 assert_eq!(view.display_text(cx), buffer.read(cx).text());
3951 });
3952 }
3953
3954 #[gpui::test]
3955 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
3956 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3957 let settings = EditorSettings::test(&cx);
3958 let (_, view) = cx.add_window(Default::default(), |cx| {
3959 build_editor(buffer.clone(), settings, cx)
3960 });
3961
3962 buffer.update(cx, |buffer, cx| {
3963 buffer.edit(
3964 vec![
3965 Point::new(1, 0)..Point::new(1, 0),
3966 Point::new(1, 1)..Point::new(1, 1),
3967 ],
3968 "\t",
3969 cx,
3970 );
3971 });
3972
3973 view.update(cx, |view, cx| {
3974 assert_eq!(
3975 view.selection_ranges(cx),
3976 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3977 );
3978
3979 view.move_down(&MoveDown, cx);
3980 assert_eq!(
3981 view.selection_ranges(cx),
3982 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3983 );
3984
3985 view.move_right(&MoveRight, cx);
3986 assert_eq!(
3987 view.selection_ranges(cx),
3988 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3989 );
3990
3991 view.move_left(&MoveLeft, cx);
3992 assert_eq!(
3993 view.selection_ranges(cx),
3994 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3995 );
3996
3997 view.move_up(&MoveUp, cx);
3998 assert_eq!(
3999 view.selection_ranges(cx),
4000 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4001 );
4002
4003 view.move_to_end(&MoveToEnd, cx);
4004 assert_eq!(
4005 view.selection_ranges(cx),
4006 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4007 );
4008
4009 view.move_to_beginning(&MoveToBeginning, cx);
4010 assert_eq!(
4011 view.selection_ranges(cx),
4012 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4013 );
4014
4015 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4016 .unwrap();
4017 view.select_to_beginning(&SelectToBeginning, cx);
4018 assert_eq!(
4019 view.selection_ranges(cx),
4020 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4021 );
4022
4023 view.select_to_end(&SelectToEnd, cx);
4024 assert_eq!(
4025 view.selection_ranges(cx),
4026 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4027 );
4028 });
4029 }
4030
4031 #[gpui::test]
4032 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4033 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4034 let settings = EditorSettings::test(&cx);
4035 let (_, view) = cx.add_window(Default::default(), |cx| {
4036 build_editor(buffer.clone(), settings, cx)
4037 });
4038
4039 assert_eq!('ⓐ'.len_utf8(), 3);
4040 assert_eq!('α'.len_utf8(), 2);
4041
4042 view.update(cx, |view, cx| {
4043 view.fold_ranges(
4044 vec![
4045 Point::new(0, 6)..Point::new(0, 12),
4046 Point::new(1, 2)..Point::new(1, 4),
4047 Point::new(2, 4)..Point::new(2, 8),
4048 ],
4049 cx,
4050 );
4051 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4052
4053 view.move_right(&MoveRight, cx);
4054 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
4055 view.move_right(&MoveRight, cx);
4056 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4057 view.move_right(&MoveRight, cx);
4058 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4059
4060 view.move_down(&MoveDown, cx);
4061 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
4062 view.move_left(&MoveLeft, cx);
4063 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
4064 view.move_left(&MoveLeft, cx);
4065 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
4066
4067 view.move_down(&MoveDown, cx);
4068 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
4069 view.move_right(&MoveRight, cx);
4070 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
4071 view.move_right(&MoveRight, cx);
4072 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
4073 view.move_right(&MoveRight, cx);
4074 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
4075
4076 view.move_up(&MoveUp, cx);
4077 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
4078 view.move_up(&MoveUp, cx);
4079 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
4080 view.move_left(&MoveLeft, cx);
4081 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4082 view.move_left(&MoveLeft, cx);
4083 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4084 view.move_left(&MoveLeft, cx);
4085 assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐ".len())]);
4086 });
4087 }
4088
4089 #[gpui::test]
4090 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4091 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4092 let settings = EditorSettings::test(&cx);
4093 let (_, view) = cx.add_window(Default::default(), |cx| {
4094 build_editor(buffer.clone(), settings, cx)
4095 });
4096 view.update(cx, |view, cx| {
4097 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4098 .unwrap();
4099
4100 view.move_down(&MoveDown, cx);
4101 assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
4102
4103 view.move_down(&MoveDown, cx);
4104 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4105
4106 view.move_down(&MoveDown, cx);
4107 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4108
4109 view.move_down(&MoveDown, cx);
4110 assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
4111
4112 view.move_up(&MoveUp, cx);
4113 assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4114
4115 view.move_up(&MoveUp, cx);
4116 assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4117 });
4118 }
4119
4120 #[gpui::test]
4121 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4122 let buffer = MultiBuffer::build_simple("abc\n def", cx);
4123 let settings = EditorSettings::test(&cx);
4124 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4125 view.update(cx, |view, cx| {
4126 view.select_display_ranges(
4127 &[
4128 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4129 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4130 ],
4131 cx,
4132 )
4133 .unwrap();
4134 });
4135
4136 view.update(cx, |view, cx| {
4137 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4138 assert_eq!(
4139 view.selection_ranges(cx),
4140 &[
4141 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4142 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4143 ]
4144 );
4145 });
4146
4147 view.update(cx, |view, cx| {
4148 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4149 assert_eq!(
4150 view.selection_ranges(cx),
4151 &[
4152 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4153 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4154 ]
4155 );
4156 });
4157
4158 view.update(cx, |view, cx| {
4159 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4160 assert_eq!(
4161 view.selection_ranges(cx),
4162 &[
4163 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4164 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4165 ]
4166 );
4167 });
4168
4169 view.update(cx, |view, cx| {
4170 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4171 assert_eq!(
4172 view.selection_ranges(cx),
4173 &[
4174 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4175 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4176 ]
4177 );
4178 });
4179
4180 // Moving to the end of line again is a no-op.
4181 view.update(cx, |view, cx| {
4182 view.move_to_end_of_line(&MoveToEndOfLine, cx);
4183 assert_eq!(
4184 view.selection_ranges(cx),
4185 &[
4186 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4187 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4188 ]
4189 );
4190 });
4191
4192 view.update(cx, |view, cx| {
4193 view.move_left(&MoveLeft, cx);
4194 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4195 assert_eq!(
4196 view.selection_ranges(cx),
4197 &[
4198 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4199 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4200 ]
4201 );
4202 });
4203
4204 view.update(cx, |view, cx| {
4205 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4206 assert_eq!(
4207 view.selection_ranges(cx),
4208 &[
4209 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4210 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4211 ]
4212 );
4213 });
4214
4215 view.update(cx, |view, cx| {
4216 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4217 assert_eq!(
4218 view.selection_ranges(cx),
4219 &[
4220 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4221 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4222 ]
4223 );
4224 });
4225
4226 view.update(cx, |view, cx| {
4227 view.select_to_end_of_line(&SelectToEndOfLine, cx);
4228 assert_eq!(
4229 view.selection_ranges(cx),
4230 &[
4231 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4232 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4233 ]
4234 );
4235 });
4236
4237 view.update(cx, |view, cx| {
4238 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4239 assert_eq!(view.display_text(cx), "ab\n de");
4240 assert_eq!(
4241 view.selection_ranges(cx),
4242 &[
4243 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4244 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4245 ]
4246 );
4247 });
4248
4249 view.update(cx, |view, cx| {
4250 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4251 assert_eq!(view.display_text(cx), "\n");
4252 assert_eq!(
4253 view.selection_ranges(cx),
4254 &[
4255 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4256 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4257 ]
4258 );
4259 });
4260 }
4261
4262 #[gpui::test]
4263 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4264 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
4265 let settings = EditorSettings::test(&cx);
4266 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4267 view.update(cx, |view, cx| {
4268 view.select_display_ranges(
4269 &[
4270 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4271 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4272 ],
4273 cx,
4274 )
4275 .unwrap();
4276 });
4277
4278 view.update(cx, |view, cx| {
4279 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4280 assert_eq!(
4281 view.selection_ranges(cx),
4282 &[
4283 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4284 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4285 ]
4286 );
4287 });
4288
4289 view.update(cx, |view, cx| {
4290 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4291 assert_eq!(
4292 view.selection_ranges(cx),
4293 &[
4294 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4295 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4296 ]
4297 );
4298 });
4299
4300 view.update(cx, |view, cx| {
4301 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4302 assert_eq!(
4303 view.selection_ranges(cx),
4304 &[
4305 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4306 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4307 ]
4308 );
4309 });
4310
4311 view.update(cx, |view, cx| {
4312 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4313 assert_eq!(
4314 view.selection_ranges(cx),
4315 &[
4316 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4317 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4318 ]
4319 );
4320 });
4321
4322 view.update(cx, |view, cx| {
4323 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4324 assert_eq!(
4325 view.selection_ranges(cx),
4326 &[
4327 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4328 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4329 ]
4330 );
4331 });
4332
4333 view.update(cx, |view, cx| {
4334 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4335 assert_eq!(
4336 view.selection_ranges(cx),
4337 &[
4338 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4339 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4340 ]
4341 );
4342 });
4343
4344 view.update(cx, |view, cx| {
4345 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4346 assert_eq!(
4347 view.selection_ranges(cx),
4348 &[
4349 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4350 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4351 ]
4352 );
4353 });
4354
4355 view.update(cx, |view, cx| {
4356 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4357 assert_eq!(
4358 view.selection_ranges(cx),
4359 &[
4360 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4361 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4362 ]
4363 );
4364 });
4365
4366 view.update(cx, |view, cx| {
4367 view.move_right(&MoveRight, cx);
4368 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4369 assert_eq!(
4370 view.selection_ranges(cx),
4371 &[
4372 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4373 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4374 ]
4375 );
4376 });
4377
4378 view.update(cx, |view, cx| {
4379 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4380 assert_eq!(
4381 view.selection_ranges(cx),
4382 &[
4383 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4384 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4385 ]
4386 );
4387 });
4388
4389 view.update(cx, |view, cx| {
4390 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4391 assert_eq!(
4392 view.selection_ranges(cx),
4393 &[
4394 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4395 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4396 ]
4397 );
4398 });
4399 }
4400
4401 #[gpui::test]
4402 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4403 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
4404 let settings = EditorSettings::test(&cx);
4405 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4406
4407 view.update(cx, |view, cx| {
4408 view.set_wrap_width(Some(140.), cx);
4409 assert_eq!(
4410 view.display_text(cx),
4411 "use one::{\n two::three::\n four::five\n};"
4412 );
4413
4414 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4415 .unwrap();
4416
4417 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4418 assert_eq!(
4419 view.selection_ranges(cx),
4420 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4421 );
4422
4423 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4424 assert_eq!(
4425 view.selection_ranges(cx),
4426 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4427 );
4428
4429 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4430 assert_eq!(
4431 view.selection_ranges(cx),
4432 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4433 );
4434
4435 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4436 assert_eq!(
4437 view.selection_ranges(cx),
4438 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4439 );
4440
4441 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4442 assert_eq!(
4443 view.selection_ranges(cx),
4444 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4445 );
4446
4447 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4448 assert_eq!(
4449 view.selection_ranges(cx),
4450 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4451 );
4452 });
4453 }
4454
4455 #[gpui::test]
4456 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4457 let buffer = MultiBuffer::build_simple("one two three four", cx);
4458 let settings = EditorSettings::test(&cx);
4459 let (_, view) = cx.add_window(Default::default(), |cx| {
4460 build_editor(buffer.clone(), settings, cx)
4461 });
4462
4463 view.update(cx, |view, cx| {
4464 view.select_display_ranges(
4465 &[
4466 // an empty selection - the preceding word fragment is deleted
4467 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4468 // characters selected - they are deleted
4469 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4470 ],
4471 cx,
4472 )
4473 .unwrap();
4474 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4475 });
4476
4477 assert_eq!(buffer.read(cx).text(), "e two te four");
4478
4479 view.update(cx, |view, cx| {
4480 view.select_display_ranges(
4481 &[
4482 // an empty selection - the following word fragment is deleted
4483 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4484 // characters selected - they are deleted
4485 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4486 ],
4487 cx,
4488 )
4489 .unwrap();
4490 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4491 });
4492
4493 assert_eq!(buffer.read(cx).text(), "e t te our");
4494 }
4495
4496 #[gpui::test]
4497 fn test_newline(cx: &mut gpui::MutableAppContext) {
4498 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
4499 let settings = EditorSettings::test(&cx);
4500 let (_, view) = cx.add_window(Default::default(), |cx| {
4501 build_editor(buffer.clone(), settings, cx)
4502 });
4503
4504 view.update(cx, |view, cx| {
4505 view.select_display_ranges(
4506 &[
4507 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4508 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4509 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4510 ],
4511 cx,
4512 )
4513 .unwrap();
4514
4515 view.newline(&Newline, cx);
4516 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
4517 });
4518 }
4519
4520 #[gpui::test]
4521 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4522 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
4523 let settings = EditorSettings::test(&cx);
4524 let (_, view) = cx.add_window(Default::default(), |cx| {
4525 build_editor(buffer.clone(), settings, cx)
4526 });
4527
4528 view.update(cx, |view, cx| {
4529 // two selections on the same line
4530 view.select_display_ranges(
4531 &[
4532 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4533 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4534 ],
4535 cx,
4536 )
4537 .unwrap();
4538
4539 // indent from mid-tabstop to full tabstop
4540 view.tab(&Tab, cx);
4541 assert_eq!(view.text(cx), " one two\nthree\n four");
4542 assert_eq!(
4543 view.selection_ranges(cx),
4544 &[
4545 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4546 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4547 ]
4548 );
4549
4550 // outdent from 1 tabstop to 0 tabstops
4551 view.outdent(&Outdent, cx);
4552 assert_eq!(view.text(cx), "one two\nthree\n four");
4553 assert_eq!(
4554 view.selection_ranges(cx),
4555 &[
4556 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4557 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4558 ]
4559 );
4560
4561 // select across line ending
4562 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4563 .unwrap();
4564
4565 // indent and outdent affect only the preceding line
4566 view.tab(&Tab, cx);
4567 assert_eq!(view.text(cx), "one two\n three\n four");
4568 assert_eq!(
4569 view.selection_ranges(cx),
4570 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4571 );
4572 view.outdent(&Outdent, cx);
4573 assert_eq!(view.text(cx), "one two\nthree\n four");
4574 assert_eq!(
4575 view.selection_ranges(cx),
4576 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4577 );
4578 });
4579 }
4580
4581 #[gpui::test]
4582 fn test_backspace(cx: &mut gpui::MutableAppContext) {
4583 let buffer =
4584 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4585 let settings = EditorSettings::test(&cx);
4586 let (_, view) = cx.add_window(Default::default(), |cx| {
4587 build_editor(buffer.clone(), settings, cx)
4588 });
4589
4590 view.update(cx, |view, cx| {
4591 view.select_display_ranges(
4592 &[
4593 // an empty selection - the preceding character is deleted
4594 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4595 // one character selected - it is deleted
4596 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4597 // a line suffix selected - it is deleted
4598 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4599 ],
4600 cx,
4601 )
4602 .unwrap();
4603 view.backspace(&Backspace, cx);
4604 });
4605
4606 assert_eq!(
4607 buffer.read(cx).text(),
4608 "oe two three\nfou five six\nseven ten\n"
4609 );
4610 }
4611
4612 #[gpui::test]
4613 fn test_delete(cx: &mut gpui::MutableAppContext) {
4614 let buffer =
4615 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4616 let settings = EditorSettings::test(&cx);
4617 let (_, view) = cx.add_window(Default::default(), |cx| {
4618 build_editor(buffer.clone(), settings, cx)
4619 });
4620
4621 view.update(cx, |view, cx| {
4622 view.select_display_ranges(
4623 &[
4624 // an empty selection - the following character is deleted
4625 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4626 // one character selected - it is deleted
4627 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4628 // a line suffix selected - it is deleted
4629 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4630 ],
4631 cx,
4632 )
4633 .unwrap();
4634 view.delete(&Delete, cx);
4635 });
4636
4637 assert_eq!(
4638 buffer.read(cx).text(),
4639 "on two three\nfou five six\nseven ten\n"
4640 );
4641 }
4642
4643 #[gpui::test]
4644 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4645 let settings = EditorSettings::test(&cx);
4646 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4647 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4648 view.update(cx, |view, cx| {
4649 view.select_display_ranges(
4650 &[
4651 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4652 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4653 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4654 ],
4655 cx,
4656 )
4657 .unwrap();
4658 view.delete_line(&DeleteLine, cx);
4659 assert_eq!(view.display_text(cx), "ghi");
4660 assert_eq!(
4661 view.selection_ranges(cx),
4662 vec![
4663 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4664 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4665 ]
4666 );
4667 });
4668
4669 let settings = EditorSettings::test(&cx);
4670 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4671 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4672 view.update(cx, |view, cx| {
4673 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4674 .unwrap();
4675 view.delete_line(&DeleteLine, cx);
4676 assert_eq!(view.display_text(cx), "ghi\n");
4677 assert_eq!(
4678 view.selection_ranges(cx),
4679 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4680 );
4681 });
4682 }
4683
4684 #[gpui::test]
4685 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4686 let settings = EditorSettings::test(&cx);
4687 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4688 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4689 view.update(cx, |view, cx| {
4690 view.select_display_ranges(
4691 &[
4692 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4693 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4694 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4695 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4696 ],
4697 cx,
4698 )
4699 .unwrap();
4700 view.duplicate_line(&DuplicateLine, cx);
4701 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4702 assert_eq!(
4703 view.selection_ranges(cx),
4704 vec![
4705 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4706 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4707 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4708 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4709 ]
4710 );
4711 });
4712
4713 let settings = EditorSettings::test(&cx);
4714 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4715 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4716 view.update(cx, |view, cx| {
4717 view.select_display_ranges(
4718 &[
4719 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4720 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4721 ],
4722 cx,
4723 )
4724 .unwrap();
4725 view.duplicate_line(&DuplicateLine, cx);
4726 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4727 assert_eq!(
4728 view.selection_ranges(cx),
4729 vec![
4730 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4731 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4732 ]
4733 );
4734 });
4735 }
4736
4737 #[gpui::test]
4738 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4739 let settings = EditorSettings::test(&cx);
4740 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
4741 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4742 view.update(cx, |view, cx| {
4743 view.fold_ranges(
4744 vec![
4745 Point::new(0, 2)..Point::new(1, 2),
4746 Point::new(2, 3)..Point::new(4, 1),
4747 Point::new(7, 0)..Point::new(8, 4),
4748 ],
4749 cx,
4750 );
4751 view.select_display_ranges(
4752 &[
4753 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4754 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4755 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4756 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
4757 ],
4758 cx,
4759 )
4760 .unwrap();
4761 assert_eq!(
4762 view.display_text(cx),
4763 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
4764 );
4765
4766 view.move_line_up(&MoveLineUp, cx);
4767 assert_eq!(
4768 view.display_text(cx),
4769 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
4770 );
4771 assert_eq!(
4772 view.selection_ranges(cx),
4773 vec![
4774 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4775 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4776 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4777 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4778 ]
4779 );
4780 });
4781
4782 view.update(cx, |view, cx| {
4783 view.move_line_down(&MoveLineDown, cx);
4784 assert_eq!(
4785 view.display_text(cx),
4786 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
4787 );
4788 assert_eq!(
4789 view.selection_ranges(cx),
4790 vec![
4791 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4792 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4793 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4794 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4795 ]
4796 );
4797 });
4798
4799 view.update(cx, |view, cx| {
4800 view.move_line_down(&MoveLineDown, cx);
4801 assert_eq!(
4802 view.display_text(cx),
4803 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
4804 );
4805 assert_eq!(
4806 view.selection_ranges(cx),
4807 vec![
4808 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4809 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4810 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4811 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4812 ]
4813 );
4814 });
4815
4816 view.update(cx, |view, cx| {
4817 view.move_line_up(&MoveLineUp, cx);
4818 assert_eq!(
4819 view.display_text(cx),
4820 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
4821 );
4822 assert_eq!(
4823 view.selection_ranges(cx),
4824 vec![
4825 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4826 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4827 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4828 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4829 ]
4830 );
4831 });
4832 }
4833
4834 #[gpui::test]
4835 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
4836 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
4837 let settings = EditorSettings::test(&cx);
4838 let view = cx
4839 .add_window(Default::default(), |cx| {
4840 build_editor(buffer.clone(), settings, cx)
4841 })
4842 .1;
4843
4844 // Cut with three selections. Clipboard text is divided into three slices.
4845 view.update(cx, |view, cx| {
4846 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
4847 view.cut(&Cut, cx);
4848 assert_eq!(view.display_text(cx), "two four six ");
4849 });
4850
4851 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
4852 view.update(cx, |view, cx| {
4853 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
4854 view.paste(&Paste, cx);
4855 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
4856 assert_eq!(
4857 view.selection_ranges(cx),
4858 &[
4859 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4860 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
4861 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
4862 ]
4863 );
4864 });
4865
4866 // Paste again but with only two cursors. Since the number of cursors doesn't
4867 // match the number of slices in the clipboard, the entire clipboard text
4868 // is pasted at each cursor.
4869 view.update(cx, |view, cx| {
4870 view.select_ranges(vec![0..0, 31..31], None, cx);
4871 view.handle_input(&Input("( ".into()), cx);
4872 view.paste(&Paste, cx);
4873 view.handle_input(&Input(") ".into()), cx);
4874 assert_eq!(
4875 view.display_text(cx),
4876 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4877 );
4878 });
4879
4880 view.update(cx, |view, cx| {
4881 view.select_ranges(vec![0..0], None, cx);
4882 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
4883 assert_eq!(
4884 view.display_text(cx),
4885 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4886 );
4887 });
4888
4889 // Cut with three selections, one of which is full-line.
4890 view.update(cx, |view, cx| {
4891 view.select_display_ranges(
4892 &[
4893 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
4894 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4895 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
4896 ],
4897 cx,
4898 )
4899 .unwrap();
4900 view.cut(&Cut, cx);
4901 assert_eq!(
4902 view.display_text(cx),
4903 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4904 );
4905 });
4906
4907 // Paste with three selections, noticing how the copied selection that was full-line
4908 // gets inserted before the second cursor.
4909 view.update(cx, |view, cx| {
4910 view.select_display_ranges(
4911 &[
4912 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4913 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4914 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
4915 ],
4916 cx,
4917 )
4918 .unwrap();
4919 view.paste(&Paste, cx);
4920 assert_eq!(
4921 view.display_text(cx),
4922 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4923 );
4924 assert_eq!(
4925 view.selection_ranges(cx),
4926 &[
4927 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4928 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4929 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
4930 ]
4931 );
4932 });
4933
4934 // Copy with a single cursor only, which writes the whole line into the clipboard.
4935 view.update(cx, |view, cx| {
4936 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
4937 .unwrap();
4938 view.copy(&Copy, cx);
4939 });
4940
4941 // Paste with three selections, noticing how the copied full-line selection is inserted
4942 // before the empty selections but replaces the selection that is non-empty.
4943 view.update(cx, |view, cx| {
4944 view.select_display_ranges(
4945 &[
4946 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4947 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
4948 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4949 ],
4950 cx,
4951 )
4952 .unwrap();
4953 view.paste(&Paste, cx);
4954 assert_eq!(
4955 view.display_text(cx),
4956 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4957 );
4958 assert_eq!(
4959 view.selection_ranges(cx),
4960 &[
4961 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4962 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4963 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
4964 ]
4965 );
4966 });
4967 }
4968
4969 #[gpui::test]
4970 fn test_select_all(cx: &mut gpui::MutableAppContext) {
4971 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
4972 let settings = EditorSettings::test(&cx);
4973 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4974 view.update(cx, |view, cx| {
4975 view.select_all(&SelectAll, cx);
4976 assert_eq!(
4977 view.selection_ranges(cx),
4978 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
4979 );
4980 });
4981 }
4982
4983 #[gpui::test]
4984 fn test_select_line(cx: &mut gpui::MutableAppContext) {
4985 let settings = EditorSettings::test(&cx);
4986 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
4987 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4988 view.update(cx, |view, cx| {
4989 view.select_display_ranges(
4990 &[
4991 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4992 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4993 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4994 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
4995 ],
4996 cx,
4997 )
4998 .unwrap();
4999 view.select_line(&SelectLine, cx);
5000 assert_eq!(
5001 view.selection_ranges(cx),
5002 vec![
5003 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5004 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5005 ]
5006 );
5007 });
5008
5009 view.update(cx, |view, cx| {
5010 view.select_line(&SelectLine, cx);
5011 assert_eq!(
5012 view.selection_ranges(cx),
5013 vec![
5014 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5015 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5016 ]
5017 );
5018 });
5019
5020 view.update(cx, |view, cx| {
5021 view.select_line(&SelectLine, cx);
5022 assert_eq!(
5023 view.selection_ranges(cx),
5024 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5025 );
5026 });
5027 }
5028
5029 #[gpui::test]
5030 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5031 let settings = EditorSettings::test(&cx);
5032 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5033 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5034 view.update(cx, |view, cx| {
5035 view.fold_ranges(
5036 vec![
5037 Point::new(0, 2)..Point::new(1, 2),
5038 Point::new(2, 3)..Point::new(4, 1),
5039 Point::new(7, 0)..Point::new(8, 4),
5040 ],
5041 cx,
5042 );
5043 view.select_display_ranges(
5044 &[
5045 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5046 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5047 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5048 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5049 ],
5050 cx,
5051 )
5052 .unwrap();
5053 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5054 });
5055
5056 view.update(cx, |view, cx| {
5057 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5058 assert_eq!(
5059 view.display_text(cx),
5060 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5061 );
5062 assert_eq!(
5063 view.selection_ranges(cx),
5064 [
5065 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5066 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5067 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5068 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5069 ]
5070 );
5071 });
5072
5073 view.update(cx, |view, cx| {
5074 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5075 .unwrap();
5076 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5077 assert_eq!(
5078 view.display_text(cx),
5079 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5080 );
5081 assert_eq!(
5082 view.selection_ranges(cx),
5083 [
5084 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5085 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5086 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5087 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5088 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5089 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5090 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5091 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5092 ]
5093 );
5094 });
5095 }
5096
5097 #[gpui::test]
5098 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5099 let settings = EditorSettings::test(&cx);
5100 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5101 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5102
5103 view.update(cx, |view, cx| {
5104 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5105 .unwrap();
5106 });
5107 view.update(cx, |view, cx| {
5108 view.add_selection_above(&AddSelectionAbove, cx);
5109 assert_eq!(
5110 view.selection_ranges(cx),
5111 vec![
5112 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5113 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5114 ]
5115 );
5116 });
5117
5118 view.update(cx, |view, cx| {
5119 view.add_selection_above(&AddSelectionAbove, cx);
5120 assert_eq!(
5121 view.selection_ranges(cx),
5122 vec![
5123 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5124 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5125 ]
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![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5134 );
5135 });
5136
5137 view.update(cx, |view, cx| {
5138 view.add_selection_below(&AddSelectionBelow, cx);
5139 assert_eq!(
5140 view.selection_ranges(cx),
5141 vec![
5142 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5143 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5144 ]
5145 );
5146 });
5147
5148 view.update(cx, |view, cx| {
5149 view.add_selection_below(&AddSelectionBelow, cx);
5150 assert_eq!(
5151 view.selection_ranges(cx),
5152 vec![
5153 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5154 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5155 ]
5156 );
5157 });
5158
5159 view.update(cx, |view, cx| {
5160 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5161 .unwrap();
5162 });
5163 view.update(cx, |view, cx| {
5164 view.add_selection_below(&AddSelectionBelow, cx);
5165 assert_eq!(
5166 view.selection_ranges(cx),
5167 vec![
5168 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5169 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5170 ]
5171 );
5172 });
5173
5174 view.update(cx, |view, cx| {
5175 view.add_selection_below(&AddSelectionBelow, cx);
5176 assert_eq!(
5177 view.selection_ranges(cx),
5178 vec![
5179 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5180 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5181 ]
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.add_selection_above(&AddSelectionAbove, cx);
5195 assert_eq!(
5196 view.selection_ranges(cx),
5197 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5198 );
5199 });
5200
5201 view.update(cx, |view, cx| {
5202 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5203 .unwrap();
5204 view.add_selection_below(&AddSelectionBelow, cx);
5205 assert_eq!(
5206 view.selection_ranges(cx),
5207 vec![
5208 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5209 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5210 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5211 ]
5212 );
5213 });
5214
5215 view.update(cx, |view, cx| {
5216 view.add_selection_below(&AddSelectionBelow, cx);
5217 assert_eq!(
5218 view.selection_ranges(cx),
5219 vec![
5220 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5221 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5222 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5223 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5224 ]
5225 );
5226 });
5227
5228 view.update(cx, |view, cx| {
5229 view.add_selection_above(&AddSelectionAbove, cx);
5230 assert_eq!(
5231 view.selection_ranges(cx),
5232 vec![
5233 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5234 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5235 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5236 ]
5237 );
5238 });
5239
5240 view.update(cx, |view, cx| {
5241 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5242 .unwrap();
5243 });
5244 view.update(cx, |view, cx| {
5245 view.add_selection_above(&AddSelectionAbove, cx);
5246 assert_eq!(
5247 view.selection_ranges(cx),
5248 vec![
5249 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5250 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5251 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5252 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5253 ]
5254 );
5255 });
5256
5257 view.update(cx, |view, cx| {
5258 view.add_selection_below(&AddSelectionBelow, cx);
5259 assert_eq!(
5260 view.selection_ranges(cx),
5261 vec![
5262 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5263 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5264 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5265 ]
5266 );
5267 });
5268 }
5269
5270 #[gpui::test]
5271 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5272 let settings = cx.read(EditorSettings::test);
5273 let language = Some(Arc::new(Language::new(
5274 LanguageConfig::default(),
5275 Some(tree_sitter_rust::language()),
5276 )));
5277
5278 let text = r#"
5279 use mod1::mod2::{mod3, mod4};
5280
5281 fn fn_1(param1: bool, param2: &str) {
5282 let var1 = "text";
5283 }
5284 "#
5285 .unindent();
5286
5287 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5288 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5289 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5290 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5291 .await;
5292
5293 view.update(&mut cx, |view, cx| {
5294 view.select_display_ranges(
5295 &[
5296 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5297 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5298 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5299 ],
5300 cx,
5301 )
5302 .unwrap();
5303 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5304 });
5305 assert_eq!(
5306 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5307 &[
5308 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5309 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5310 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5311 ]
5312 );
5313
5314 view.update(&mut cx, |view, cx| {
5315 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5316 });
5317 assert_eq!(
5318 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5319 &[
5320 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5321 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5322 ]
5323 );
5324
5325 view.update(&mut cx, |view, cx| {
5326 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5327 });
5328 assert_eq!(
5329 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5330 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5331 );
5332
5333 // Trying to expand the selected syntax node one more time has no effect.
5334 view.update(&mut cx, |view, cx| {
5335 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5336 });
5337 assert_eq!(
5338 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5339 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5340 );
5341
5342 view.update(&mut cx, |view, cx| {
5343 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5344 });
5345 assert_eq!(
5346 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5347 &[
5348 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5349 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5350 ]
5351 );
5352
5353 view.update(&mut cx, |view, cx| {
5354 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5355 });
5356 assert_eq!(
5357 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5358 &[
5359 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5360 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5361 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5362 ]
5363 );
5364
5365 view.update(&mut cx, |view, cx| {
5366 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5367 });
5368 assert_eq!(
5369 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5370 &[
5371 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5372 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5373 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5374 ]
5375 );
5376
5377 // Trying to shrink the selected syntax node one more time has no effect.
5378 view.update(&mut cx, |view, cx| {
5379 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5380 });
5381 assert_eq!(
5382 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5383 &[
5384 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5385 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5386 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5387 ]
5388 );
5389
5390 // Ensure that we keep expanding the selection if the larger selection starts or ends within
5391 // a fold.
5392 view.update(&mut cx, |view, cx| {
5393 view.fold_ranges(
5394 vec![
5395 Point::new(0, 21)..Point::new(0, 24),
5396 Point::new(3, 20)..Point::new(3, 22),
5397 ],
5398 cx,
5399 );
5400 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5401 });
5402 assert_eq!(
5403 view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5404 &[
5405 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5406 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5407 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5408 ]
5409 );
5410 }
5411
5412 #[gpui::test]
5413 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5414 let settings = cx.read(EditorSettings::test);
5415 let language = Some(Arc::new(Language::new(
5416 LanguageConfig {
5417 brackets: vec![
5418 BracketPair {
5419 start: "{".to_string(),
5420 end: "}".to_string(),
5421 close: true,
5422 newline: true,
5423 },
5424 BracketPair {
5425 start: "/*".to_string(),
5426 end: " */".to_string(),
5427 close: true,
5428 newline: true,
5429 },
5430 ],
5431 ..Default::default()
5432 },
5433 Some(tree_sitter_rust::language()),
5434 )));
5435
5436 let text = r#"
5437 a
5438
5439 /
5440
5441 "#
5442 .unindent();
5443
5444 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5445 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5446 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5447 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5448 .await;
5449
5450 view.update(&mut cx, |view, cx| {
5451 view.select_display_ranges(
5452 &[
5453 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5454 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5455 ],
5456 cx,
5457 )
5458 .unwrap();
5459 view.handle_input(&Input("{".to_string()), cx);
5460 view.handle_input(&Input("{".to_string()), cx);
5461 view.handle_input(&Input("{".to_string()), cx);
5462 assert_eq!(
5463 view.text(cx),
5464 "
5465 {{{}}}
5466 {{{}}}
5467 /
5468
5469 "
5470 .unindent()
5471 );
5472
5473 view.move_right(&MoveRight, cx);
5474 view.handle_input(&Input("}".to_string()), cx);
5475 view.handle_input(&Input("}".to_string()), cx);
5476 view.handle_input(&Input("}".to_string()), cx);
5477 assert_eq!(
5478 view.text(cx),
5479 "
5480 {{{}}}}
5481 {{{}}}}
5482 /
5483
5484 "
5485 .unindent()
5486 );
5487
5488 view.undo(&Undo, cx);
5489 view.handle_input(&Input("/".to_string()), cx);
5490 view.handle_input(&Input("*".to_string()), cx);
5491 assert_eq!(
5492 view.text(cx),
5493 "
5494 /* */
5495 /* */
5496 /
5497
5498 "
5499 .unindent()
5500 );
5501
5502 view.undo(&Undo, cx);
5503 view.select_display_ranges(
5504 &[
5505 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5506 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5507 ],
5508 cx,
5509 )
5510 .unwrap();
5511 view.handle_input(&Input("*".to_string()), cx);
5512 assert_eq!(
5513 view.text(cx),
5514 "
5515 a
5516
5517 /*
5518 *
5519 "
5520 .unindent()
5521 );
5522 });
5523 }
5524
5525 #[gpui::test]
5526 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5527 let settings = cx.read(EditorSettings::test);
5528 let language = Some(Arc::new(Language::new(
5529 LanguageConfig {
5530 line_comment: Some("// ".to_string()),
5531 ..Default::default()
5532 },
5533 Some(tree_sitter_rust::language()),
5534 )));
5535
5536 let text = "
5537 fn a() {
5538 //b();
5539 // c();
5540 // d();
5541 }
5542 "
5543 .unindent();
5544
5545 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5546 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5547 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5548
5549 view.update(&mut cx, |editor, cx| {
5550 // If multiple selections intersect a line, the line is only
5551 // toggled once.
5552 editor
5553 .select_display_ranges(
5554 &[
5555 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5556 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5557 ],
5558 cx,
5559 )
5560 .unwrap();
5561 editor.toggle_comments(&ToggleComments, cx);
5562 assert_eq!(
5563 editor.text(cx),
5564 "
5565 fn a() {
5566 b();
5567 c();
5568 d();
5569 }
5570 "
5571 .unindent()
5572 );
5573
5574 // The comment prefix is inserted at the same column for every line
5575 // in a selection.
5576 editor
5577 .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5578 .unwrap();
5579 editor.toggle_comments(&ToggleComments, cx);
5580 assert_eq!(
5581 editor.text(cx),
5582 "
5583 fn a() {
5584 // b();
5585 // c();
5586 // d();
5587 }
5588 "
5589 .unindent()
5590 );
5591
5592 // If a selection ends at the beginning of a line, that line is not toggled.
5593 editor
5594 .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
5595 .unwrap();
5596 editor.toggle_comments(&ToggleComments, cx);
5597 assert_eq!(
5598 editor.text(cx),
5599 "
5600 fn a() {
5601 // b();
5602 c();
5603 // d();
5604 }
5605 "
5606 .unindent()
5607 );
5608 });
5609 }
5610
5611 #[gpui::test]
5612 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
5613 let settings = cx.read(EditorSettings::test);
5614 let language = Some(Arc::new(Language::new(
5615 LanguageConfig {
5616 brackets: vec![
5617 BracketPair {
5618 start: "{".to_string(),
5619 end: "}".to_string(),
5620 close: true,
5621 newline: true,
5622 },
5623 BracketPair {
5624 start: "/* ".to_string(),
5625 end: " */".to_string(),
5626 close: true,
5627 newline: true,
5628 },
5629 ],
5630 ..Default::default()
5631 },
5632 Some(tree_sitter_rust::language()),
5633 )));
5634
5635 let text = concat!(
5636 "{ }\n", // Suppress rustfmt
5637 " x\n", //
5638 " /* */\n", //
5639 "x\n", //
5640 "{{} }\n", //
5641 );
5642
5643 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5644 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5645 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5646 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5647 .await;
5648
5649 view.update(&mut cx, |view, cx| {
5650 view.select_display_ranges(
5651 &[
5652 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5653 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5654 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5655 ],
5656 cx,
5657 )
5658 .unwrap();
5659 view.newline(&Newline, cx);
5660
5661 assert_eq!(
5662 view.buffer().read(cx).text(),
5663 concat!(
5664 "{ \n", // Suppress rustfmt
5665 "\n", //
5666 "}\n", //
5667 " x\n", //
5668 " /* \n", //
5669 " \n", //
5670 " */\n", //
5671 "x\n", //
5672 "{{} \n", //
5673 "}\n", //
5674 )
5675 );
5676 });
5677 }
5678
5679 impl Editor {
5680 fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
5681 self.intersecting_selections(
5682 self.selection_set_id,
5683 DisplayPoint::zero()..self.max_point(cx),
5684 cx,
5685 )
5686 .into_iter()
5687 .map(|s| {
5688 if s.reversed {
5689 s.end..s.start
5690 } else {
5691 s.start..s.end
5692 }
5693 })
5694 .collect()
5695 }
5696 }
5697
5698 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
5699 let point = DisplayPoint::new(row as u32, column as u32);
5700 point..point
5701 }
5702
5703 fn build_editor(
5704 buffer: ModelHandle<MultiBuffer>,
5705 settings: EditorSettings,
5706 cx: &mut ViewContext<Editor>,
5707 ) -> Editor {
5708 Editor::for_buffer(buffer, move |_| settings.clone(), cx)
5709 }
5710}
5711
5712trait RangeExt<T> {
5713 fn sorted(&self) -> Range<T>;
5714 fn to_inclusive(&self) -> RangeInclusive<T>;
5715}
5716
5717impl<T: Ord + Clone> RangeExt<T> for Range<T> {
5718 fn sorted(&self) -> Self {
5719 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
5720 }
5721
5722 fn to_inclusive(&self) -> RangeInclusive<T> {
5723 self.start.clone()..=self.end.clone()
5724 }
5725}