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