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