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