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