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