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