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