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