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