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