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