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