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