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.transact(cx, |this, cx| {
1748 if !this.surround_with_bracket_pair(text, cx) {
1749 this.insert(text, cx);
1750 this.autoclose_bracket_pairs(cx);
1751 }
1752 });
1753 self.trigger_completion_on_input(text, cx);
1754 }
1755 }
1756
1757 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
1758 self.transact(cx, |this, cx| {
1759 let mut old_selections = SmallVec::<[_; 32]>::new();
1760 {
1761 let selections = this.local_selections::<usize>(cx);
1762 let buffer = this.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)
1793 .saturating_sub(pair_start.len()),
1794 pair_start,
1795 )
1796 });
1797 }
1798
1799 old_selections.push((
1800 selection.id,
1801 buffer.anchor_after(end),
1802 start..end,
1803 indent,
1804 insert_extra_newline,
1805 ));
1806 }
1807 }
1808
1809 this.buffer.update(cx, |buffer, cx| {
1810 let mut delta = 0_isize;
1811 let mut pending_edit: Option<PendingEdit> = None;
1812 for (_, _, range, indent, insert_extra_newline) in &old_selections {
1813 if pending_edit.as_ref().map_or(false, |pending| {
1814 pending.indent != *indent
1815 || pending.insert_extra_newline != *insert_extra_newline
1816 }) {
1817 let pending = pending_edit.take().unwrap();
1818 let mut new_text = String::with_capacity(1 + pending.indent as usize);
1819 new_text.push('\n');
1820 new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1821 if pending.insert_extra_newline {
1822 new_text = new_text.repeat(2);
1823 }
1824 buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1825 delta += pending.delta;
1826 }
1827
1828 let start = (range.start as isize + delta) as usize;
1829 let end = (range.end as isize + delta) as usize;
1830 let mut text_len = *indent as usize + 1;
1831 if *insert_extra_newline {
1832 text_len *= 2;
1833 }
1834
1835 let pending = pending_edit.get_or_insert_with(Default::default);
1836 pending.delta += text_len as isize - (end - start) as isize;
1837 pending.indent = *indent;
1838 pending.insert_extra_newline = *insert_extra_newline;
1839 pending.ranges.push(start..end);
1840 }
1841
1842 let pending = pending_edit.unwrap();
1843 let mut new_text = String::with_capacity(1 + pending.indent as usize);
1844 new_text.push('\n');
1845 new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1846 if pending.insert_extra_newline {
1847 new_text = new_text.repeat(2);
1848 }
1849 buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1850
1851 let buffer = buffer.read(cx);
1852 this.selections = this
1853 .selections
1854 .iter()
1855 .cloned()
1856 .zip(old_selections)
1857 .map(
1858 |(mut new_selection, (_, end_anchor, _, _, insert_extra_newline))| {
1859 let mut cursor = end_anchor.to_point(&buffer);
1860 if insert_extra_newline {
1861 cursor.row -= 1;
1862 cursor.column = buffer.line_len(cursor.row);
1863 }
1864 let anchor = buffer.anchor_after(cursor);
1865 new_selection.start = anchor.clone();
1866 new_selection.end = anchor;
1867 new_selection
1868 },
1869 )
1870 .collect();
1871 });
1872
1873 this.request_autoscroll(Autoscroll::Fit, cx);
1874 });
1875
1876 #[derive(Default)]
1877 struct PendingEdit {
1878 indent: u32,
1879 insert_extra_newline: bool,
1880 delta: isize,
1881 ranges: SmallVec<[Range<usize>; 32]>,
1882 }
1883 }
1884
1885 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
1886 self.transact(cx, |this, cx| {
1887 let old_selections = this.local_selections::<usize>(cx);
1888 let selection_anchors = this.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 = this.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 this.update_selections(selections, Some(Autoscroll::Fit), cx);
1918 });
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.transact(cx, |this, 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 this.insert_snippet(&ranges, snippet, cx).log_err();
2296 } else {
2297 this.buffer.update(cx, |buffer, cx| {
2298 buffer.edit_with_autoindent(ranges, text, cx);
2299 });
2300 }
2301 });
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.transact(cx, |this, cx| {
2751 this.select_all(&SelectAll, cx);
2752 this.insert("", cx);
2753 });
2754 }
2755
2756 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
2757 let mut selections = self.local_selections::<Point>(cx);
2758 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2759 for selection in &mut selections {
2760 if selection.is_empty() {
2761 let old_head = selection.head();
2762 let mut new_head =
2763 movement::left(&display_map, old_head.to_display_point(&display_map))
2764 .to_point(&display_map);
2765 if let Some((buffer, line_buffer_range)) = display_map
2766 .buffer_snapshot
2767 .buffer_line_for_row(old_head.row)
2768 {
2769 let indent_column = buffer.indent_column_for_line(line_buffer_range.start.row);
2770 if old_head.column <= indent_column && old_head.column > 0 {
2771 let indent = buffer.indent_size();
2772 new_head = cmp::min(
2773 new_head,
2774 Point::new(old_head.row, ((old_head.column - 1) / indent) * indent),
2775 );
2776 }
2777 }
2778
2779 selection.set_head(new_head, SelectionGoal::None);
2780 }
2781 }
2782
2783 self.transact(cx, |this, cx| {
2784 this.update_selections(selections, Some(Autoscroll::Fit), cx);
2785 this.insert("", cx);
2786 });
2787 }
2788
2789 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
2790 self.transact(cx, |this, cx| {
2791 this.move_selections(cx, |map, selection| {
2792 if selection.is_empty() {
2793 let cursor = movement::right(map, selection.head());
2794 selection.set_head(cursor, SelectionGoal::None);
2795 }
2796 });
2797 this.insert(&"", cx);
2798 });
2799 }
2800
2801 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
2802 if self.move_to_next_snippet_tabstop(cx) {
2803 return;
2804 }
2805
2806 let tab_size = cx.global::<Settings>().tab_size;
2807 let mut selections = self.local_selections::<Point>(cx);
2808 self.transact(cx, |this, cx| {
2809 let mut last_indent = None;
2810 this.buffer.update(cx, |buffer, cx| {
2811 for selection in &mut selections {
2812 if selection.is_empty() {
2813 let char_column = buffer
2814 .read(cx)
2815 .text_for_range(Point::new(selection.start.row, 0)..selection.start)
2816 .flat_map(str::chars)
2817 .count();
2818 let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
2819 buffer.edit(
2820 [selection.start..selection.start],
2821 " ".repeat(chars_to_next_tab_stop),
2822 cx,
2823 );
2824 selection.start.column += chars_to_next_tab_stop as u32;
2825 selection.end = selection.start;
2826 } else {
2827 let mut start_row = selection.start.row;
2828 let mut end_row = selection.end.row + 1;
2829
2830 // If a selection ends at the beginning of a line, don't indent
2831 // that last line.
2832 if selection.end.column == 0 {
2833 end_row -= 1;
2834 }
2835
2836 // Avoid re-indenting a row that has already been indented by a
2837 // previous selection, but still update this selection's column
2838 // to reflect that indentation.
2839 if let Some((last_indent_row, last_indent_len)) = last_indent {
2840 if last_indent_row == selection.start.row {
2841 selection.start.column += last_indent_len;
2842 start_row += 1;
2843 }
2844 if last_indent_row == selection.end.row {
2845 selection.end.column += last_indent_len;
2846 }
2847 }
2848
2849 for row in start_row..end_row {
2850 let indent_column =
2851 buffer.read(cx).indent_column_for_line(row) as usize;
2852 let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
2853 let row_start = Point::new(row, 0);
2854 buffer.edit(
2855 [row_start..row_start],
2856 " ".repeat(columns_to_next_tab_stop),
2857 cx,
2858 );
2859
2860 // Update this selection's endpoints to reflect the indentation.
2861 if row == selection.start.row {
2862 selection.start.column += columns_to_next_tab_stop as u32;
2863 }
2864 if row == selection.end.row {
2865 selection.end.column += columns_to_next_tab_stop as u32;
2866 }
2867
2868 last_indent = Some((row, columns_to_next_tab_stop as u32));
2869 }
2870 }
2871 }
2872 });
2873
2874 this.update_selections(selections, Some(Autoscroll::Fit), cx);
2875 });
2876 }
2877
2878 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
2879 if !self.snippet_stack.is_empty() {
2880 self.move_to_prev_snippet_tabstop(cx);
2881 return;
2882 }
2883
2884 let tab_size = cx.global::<Settings>().tab_size;
2885 let selections = self.local_selections::<Point>(cx);
2886 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2887 let mut deletion_ranges = Vec::new();
2888 let mut last_outdent = None;
2889 {
2890 let buffer = self.buffer.read(cx).read(cx);
2891 for selection in &selections {
2892 let mut rows = selection.spanned_rows(false, &display_map);
2893
2894 // Avoid re-outdenting a row that has already been outdented by a
2895 // previous selection.
2896 if let Some(last_row) = last_outdent {
2897 if last_row == rows.start {
2898 rows.start += 1;
2899 }
2900 }
2901
2902 for row in rows {
2903 let column = buffer.indent_column_for_line(row) as usize;
2904 if column > 0 {
2905 let mut deletion_len = (column % tab_size) as u32;
2906 if deletion_len == 0 {
2907 deletion_len = tab_size as u32;
2908 }
2909 deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
2910 last_outdent = Some(row);
2911 }
2912 }
2913 }
2914 }
2915
2916 self.transact(cx, |this, cx| {
2917 this.buffer.update(cx, |buffer, cx| {
2918 buffer.edit(deletion_ranges, "", cx);
2919 });
2920 this.update_selections(
2921 this.local_selections::<usize>(cx),
2922 Some(Autoscroll::Fit),
2923 cx,
2924 );
2925 });
2926 }
2927
2928 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
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 self.transact(cx, |this, cx| {
2979 let buffer = this.buffer.update(cx, |buffer, cx| {
2980 buffer.edit(edit_ranges, "", cx);
2981 buffer.snapshot(cx)
2982 });
2983 let new_selections = new_cursors
2984 .into_iter()
2985 .map(|(id, cursor)| {
2986 let cursor = cursor.to_point(&buffer);
2987 Selection {
2988 id,
2989 start: cursor,
2990 end: cursor,
2991 reversed: false,
2992 goal: SelectionGoal::None,
2993 }
2994 })
2995 .collect();
2996 this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2997 });
2998 }
2999
3000 pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
3001 let selections = self.local_selections::<Point>(cx);
3002 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3003 let buffer = &display_map.buffer_snapshot;
3004
3005 let mut edits = Vec::new();
3006 let mut selections_iter = selections.iter().peekable();
3007 while let Some(selection) = selections_iter.next() {
3008 // Avoid duplicating the same lines twice.
3009 let mut rows = selection.spanned_rows(false, &display_map);
3010
3011 while let Some(next_selection) = selections_iter.peek() {
3012 let next_rows = next_selection.spanned_rows(false, &display_map);
3013 if next_rows.start <= rows.end - 1 {
3014 rows.end = next_rows.end;
3015 selections_iter.next().unwrap();
3016 } else {
3017 break;
3018 }
3019 }
3020
3021 // Copy the text from the selected row region and splice it at the start of the region.
3022 let start = Point::new(rows.start, 0);
3023 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
3024 let text = buffer
3025 .text_for_range(start..end)
3026 .chain(Some("\n"))
3027 .collect::<String>();
3028 edits.push((start, text, rows.len() as u32));
3029 }
3030
3031 self.transact(cx, |this, cx| {
3032 this.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 this.request_autoscroll(Autoscroll::Fit, cx);
3039 });
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.transact(cx, |this, cx| {
3141 this.unfold_ranges(unfold_ranges, cx);
3142 this.buffer.update(cx, |buffer, cx| {
3143 for (range, text) in edits {
3144 buffer.edit([range], text, cx);
3145 }
3146 });
3147 this.fold_ranges(refold_ranges, cx);
3148 this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3149 });
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.transact(cx, |this, cx| {
3244 this.unfold_ranges(unfold_ranges, cx);
3245 this.buffer.update(cx, |buffer, cx| {
3246 for (range, text) in edits {
3247 buffer.edit([range], text, cx);
3248 }
3249 });
3250 this.fold_ranges(refold_ranges, cx);
3251 this.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3252 });
3253 }
3254
3255 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
3256 let mut text = String::new();
3257 let mut selections = self.local_selections::<Point>(cx);
3258 let mut clipboard_selections = Vec::with_capacity(selections.len());
3259 {
3260 let buffer = self.buffer.read(cx).read(cx);
3261 let max_point = buffer.max_point();
3262 for selection in &mut selections {
3263 let is_entire_line = selection.is_empty();
3264 if is_entire_line {
3265 selection.start = Point::new(selection.start.row, 0);
3266 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
3267 selection.goal = SelectionGoal::None;
3268 }
3269 let mut len = 0;
3270 for chunk in buffer.text_for_range(selection.start..selection.end) {
3271 text.push_str(chunk);
3272 len += chunk.len();
3273 }
3274 clipboard_selections.push(ClipboardSelection {
3275 len,
3276 is_entire_line,
3277 });
3278 }
3279 }
3280
3281 self.transact(cx, |this, cx| {
3282 this.update_selections(selections, Some(Autoscroll::Fit), cx);
3283 this.insert("", cx);
3284 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
3285 });
3286 }
3287
3288 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
3289 let selections = self.local_selections::<Point>(cx);
3290 let mut text = String::new();
3291 let mut clipboard_selections = Vec::with_capacity(selections.len());
3292 {
3293 let buffer = self.buffer.read(cx).read(cx);
3294 let max_point = buffer.max_point();
3295 for selection in selections.iter() {
3296 let mut start = selection.start;
3297 let mut end = selection.end;
3298 let is_entire_line = selection.is_empty();
3299 if is_entire_line {
3300 start = Point::new(start.row, 0);
3301 end = cmp::min(max_point, Point::new(start.row + 1, 0));
3302 }
3303 let mut len = 0;
3304 for chunk in buffer.text_for_range(start..end) {
3305 text.push_str(chunk);
3306 len += chunk.len();
3307 }
3308 clipboard_selections.push(ClipboardSelection {
3309 len,
3310 is_entire_line,
3311 });
3312 }
3313 }
3314
3315 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
3316 }
3317
3318 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
3319 self.transact(cx, |this, cx| {
3320 if let Some(item) = cx.as_mut().read_from_clipboard() {
3321 let clipboard_text = item.text();
3322 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
3323 let mut selections = this.local_selections::<usize>(cx);
3324 let all_selections_were_entire_line =
3325 clipboard_selections.iter().all(|s| s.is_entire_line);
3326 if clipboard_selections.len() != selections.len() {
3327 clipboard_selections.clear();
3328 }
3329
3330 let mut delta = 0_isize;
3331 let mut start_offset = 0;
3332 for (i, selection) in selections.iter_mut().enumerate() {
3333 let to_insert;
3334 let entire_line;
3335 if let Some(clipboard_selection) = clipboard_selections.get(i) {
3336 let end_offset = start_offset + clipboard_selection.len;
3337 to_insert = &clipboard_text[start_offset..end_offset];
3338 entire_line = clipboard_selection.is_entire_line;
3339 start_offset = end_offset
3340 } else {
3341 to_insert = clipboard_text.as_str();
3342 entire_line = all_selections_were_entire_line;
3343 }
3344
3345 selection.start = (selection.start as isize + delta) as usize;
3346 selection.end = (selection.end as isize + delta) as usize;
3347
3348 this.buffer.update(cx, |buffer, cx| {
3349 // If the corresponding selection was empty when this slice of the
3350 // clipboard text was written, then the entire line containing the
3351 // selection was copied. If this selection is also currently empty,
3352 // then paste the line before the current line of the buffer.
3353 let range = if selection.is_empty() && entire_line {
3354 let column =
3355 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 this.update_selections(selections, Some(Autoscroll::Fit), cx);
3369 } else {
3370 this.insert(clipboard_text, cx);
3371 }
3372 }
3373 });
3374 }
3375
3376 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
3377 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
3378 if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
3379 self.set_selections(selections, None, true, cx);
3380 }
3381 self.request_autoscroll(Autoscroll::Fit, cx);
3382 cx.emit(Event::Edited);
3383 }
3384 }
3385
3386 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
3387 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
3388 if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
3389 self.set_selections(selections, None, true, cx);
3390 }
3391 self.request_autoscroll(Autoscroll::Fit, cx);
3392 cx.emit(Event::Edited);
3393 }
3394 }
3395
3396 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
3397 self.buffer
3398 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3399 }
3400
3401 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
3402 self.move_selections(cx, |map, selection| {
3403 let cursor = if selection.is_empty() {
3404 movement::left(map, selection.start)
3405 } else {
3406 selection.start
3407 };
3408 selection.collapse_to(cursor, SelectionGoal::None);
3409 });
3410 }
3411
3412 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
3413 self.move_selection_heads(cx, |map, head, _| {
3414 (movement::left(map, head), SelectionGoal::None)
3415 });
3416 }
3417
3418 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
3419 self.move_selections(cx, |map, selection| {
3420 let cursor = if selection.is_empty() {
3421 movement::right(map, selection.end)
3422 } else {
3423 selection.end
3424 };
3425 selection.collapse_to(cursor, SelectionGoal::None)
3426 });
3427 }
3428
3429 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
3430 self.move_selection_heads(cx, |map, head, _| {
3431 (movement::right(map, head), SelectionGoal::None)
3432 });
3433 }
3434
3435 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
3436 if self.take_rename(true, cx).is_some() {
3437 return;
3438 }
3439
3440 if let Some(context_menu) = self.context_menu.as_mut() {
3441 if context_menu.select_prev(cx) {
3442 return;
3443 }
3444 }
3445
3446 if matches!(self.mode, EditorMode::SingleLine) {
3447 cx.propagate_action();
3448 return;
3449 }
3450
3451 self.move_selections(cx, |map, selection| {
3452 if !selection.is_empty() {
3453 selection.goal = SelectionGoal::None;
3454 }
3455 let (cursor, goal) = movement::up(&map, selection.start, selection.goal);
3456 selection.collapse_to(cursor, goal);
3457 });
3458 }
3459
3460 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
3461 self.move_selection_heads(cx, movement::up)
3462 }
3463
3464 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
3465 self.take_rename(true, cx);
3466
3467 if let Some(context_menu) = self.context_menu.as_mut() {
3468 if context_menu.select_next(cx) {
3469 return;
3470 }
3471 }
3472
3473 if matches!(self.mode, EditorMode::SingleLine) {
3474 cx.propagate_action();
3475 return;
3476 }
3477
3478 self.move_selections(cx, |map, selection| {
3479 if !selection.is_empty() {
3480 selection.goal = SelectionGoal::None;
3481 }
3482 let (cursor, goal) = movement::down(&map, selection.end, selection.goal);
3483 selection.collapse_to(cursor, goal);
3484 });
3485 }
3486
3487 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
3488 self.move_selection_heads(cx, movement::down)
3489 }
3490
3491 pub fn move_to_previous_word_start(
3492 &mut self,
3493 _: &MoveToPreviousWordStart,
3494 cx: &mut ViewContext<Self>,
3495 ) {
3496 self.move_cursors(cx, |map, head, _| {
3497 (
3498 movement::previous_word_start(map, head),
3499 SelectionGoal::None,
3500 )
3501 });
3502 }
3503
3504 pub fn select_to_previous_word_start(
3505 &mut self,
3506 _: &SelectToPreviousWordBoundary,
3507 cx: &mut ViewContext<Self>,
3508 ) {
3509 self.move_selection_heads(cx, |map, head, _| {
3510 (
3511 movement::previous_word_start(map, head),
3512 SelectionGoal::None,
3513 )
3514 });
3515 }
3516
3517 pub fn delete_to_previous_word_start(
3518 &mut self,
3519 _: &DeleteToPreviousWordBoundary,
3520 cx: &mut ViewContext<Self>,
3521 ) {
3522 self.transact(cx, |this, cx| {
3523 this.move_selections(cx, |map, selection| {
3524 if selection.is_empty() {
3525 let cursor = movement::previous_word_start(map, selection.head());
3526 selection.set_head(cursor, SelectionGoal::None);
3527 }
3528 });
3529 this.insert("", cx);
3530 });
3531 }
3532
3533 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
3534 self.move_cursors(cx, |map, head, _| {
3535 (movement::next_word_end(map, head), SelectionGoal::None)
3536 });
3537 }
3538
3539 pub fn select_to_next_word_end(
3540 &mut self,
3541 _: &SelectToNextWordBoundary,
3542 cx: &mut ViewContext<Self>,
3543 ) {
3544 self.move_selection_heads(cx, |map, head, _| {
3545 (movement::next_word_end(map, head), SelectionGoal::None)
3546 });
3547 }
3548
3549 pub fn delete_to_next_word_end(
3550 &mut self,
3551 _: &DeleteToNextWordBoundary,
3552 cx: &mut ViewContext<Self>,
3553 ) {
3554 self.transact(cx, |this, cx| {
3555 this.move_selections(cx, |map, selection| {
3556 if selection.is_empty() {
3557 let cursor = movement::next_word_end(map, selection.head());
3558 selection.set_head(cursor, SelectionGoal::None);
3559 }
3560 });
3561 this.insert("", cx);
3562 });
3563 }
3564
3565 pub fn move_to_beginning_of_line(
3566 &mut self,
3567 _: &MoveToBeginningOfLine,
3568 cx: &mut ViewContext<Self>,
3569 ) {
3570 self.move_cursors(cx, |map, head, _| {
3571 (
3572 movement::line_beginning(map, head, true),
3573 SelectionGoal::None,
3574 )
3575 });
3576 }
3577
3578 pub fn select_to_beginning_of_line(
3579 &mut self,
3580 SelectToBeginningOfLine(stop_at_soft_boundaries): &SelectToBeginningOfLine,
3581 cx: &mut ViewContext<Self>,
3582 ) {
3583 self.move_selection_heads(cx, |map, head, _| {
3584 (
3585 movement::line_beginning(map, head, *stop_at_soft_boundaries),
3586 SelectionGoal::None,
3587 )
3588 });
3589 }
3590
3591 pub fn delete_to_beginning_of_line(
3592 &mut self,
3593 _: &DeleteToBeginningOfLine,
3594 cx: &mut ViewContext<Self>,
3595 ) {
3596 self.transact(cx, |this, cx| {
3597 this.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
3598 this.backspace(&Backspace, cx);
3599 });
3600 }
3601
3602 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
3603 self.move_cursors(cx, |map, head, _| {
3604 (movement::line_end(map, head, true), SelectionGoal::None)
3605 });
3606 }
3607
3608 pub fn select_to_end_of_line(
3609 &mut self,
3610 SelectToEndOfLine(stop_at_soft_boundaries): &SelectToEndOfLine,
3611 cx: &mut ViewContext<Self>,
3612 ) {
3613 self.move_selection_heads(cx, |map, head, _| {
3614 (
3615 movement::line_end(map, head, *stop_at_soft_boundaries),
3616 SelectionGoal::None,
3617 )
3618 });
3619 }
3620
3621 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
3622 self.transact(cx, |this, cx| {
3623 this.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3624 this.delete(&Delete, cx);
3625 });
3626 }
3627
3628 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
3629 self.transact(cx, |this, cx| {
3630 this.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3631 this.cut(&Cut, cx);
3632 });
3633 }
3634
3635 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
3636 if matches!(self.mode, EditorMode::SingleLine) {
3637 cx.propagate_action();
3638 return;
3639 }
3640
3641 let selection = Selection {
3642 id: post_inc(&mut self.next_selection_id),
3643 start: 0,
3644 end: 0,
3645 reversed: false,
3646 goal: SelectionGoal::None,
3647 };
3648 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3649 }
3650
3651 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
3652 let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
3653 selection.set_head(Point::zero(), SelectionGoal::None);
3654 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3655 }
3656
3657 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
3658 if matches!(self.mode, EditorMode::SingleLine) {
3659 cx.propagate_action();
3660 return;
3661 }
3662
3663 let cursor = self.buffer.read(cx).read(cx).len();
3664 let selection = Selection {
3665 id: post_inc(&mut self.next_selection_id),
3666 start: cursor,
3667 end: cursor,
3668 reversed: false,
3669 goal: SelectionGoal::None,
3670 };
3671 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3672 }
3673
3674 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
3675 self.nav_history = nav_history;
3676 }
3677
3678 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
3679 self.nav_history.as_ref()
3680 }
3681
3682 fn push_to_nav_history(
3683 &self,
3684 position: Anchor,
3685 new_position: Option<Point>,
3686 cx: &mut ViewContext<Self>,
3687 ) {
3688 if let Some(nav_history) = &self.nav_history {
3689 let buffer = self.buffer.read(cx).read(cx);
3690 let offset = position.to_offset(&buffer);
3691 let point = position.to_point(&buffer);
3692 drop(buffer);
3693
3694 if let Some(new_position) = new_position {
3695 let row_delta = (new_position.row as i64 - point.row as i64).abs();
3696 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
3697 return;
3698 }
3699 }
3700
3701 nav_history.push(Some(NavigationData {
3702 anchor: position,
3703 offset,
3704 }));
3705 }
3706 }
3707
3708 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
3709 let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
3710 selection.set_head(self.buffer.read(cx).read(cx).len(), SelectionGoal::None);
3711 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3712 }
3713
3714 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
3715 let selection = Selection {
3716 id: post_inc(&mut self.next_selection_id),
3717 start: 0,
3718 end: self.buffer.read(cx).read(cx).len(),
3719 reversed: false,
3720 goal: SelectionGoal::None,
3721 };
3722 self.update_selections(vec![selection], None, cx);
3723 }
3724
3725 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
3726 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3727 let mut selections = self.local_selections::<Point>(cx);
3728 let max_point = display_map.buffer_snapshot.max_point();
3729 for selection in &mut selections {
3730 let rows = selection.spanned_rows(true, &display_map);
3731 selection.start = Point::new(rows.start, 0);
3732 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
3733 selection.reversed = false;
3734 }
3735 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3736 }
3737
3738 pub fn split_selection_into_lines(
3739 &mut self,
3740 _: &SplitSelectionIntoLines,
3741 cx: &mut ViewContext<Self>,
3742 ) {
3743 let mut to_unfold = Vec::new();
3744 let mut new_selections = Vec::new();
3745 {
3746 let selections = self.local_selections::<Point>(cx);
3747 let buffer = self.buffer.read(cx).read(cx);
3748 for selection in selections {
3749 for row in selection.start.row..selection.end.row {
3750 let cursor = Point::new(row, buffer.line_len(row));
3751 new_selections.push(Selection {
3752 id: post_inc(&mut self.next_selection_id),
3753 start: cursor,
3754 end: cursor,
3755 reversed: false,
3756 goal: SelectionGoal::None,
3757 });
3758 }
3759 new_selections.push(Selection {
3760 id: selection.id,
3761 start: selection.end,
3762 end: selection.end,
3763 reversed: false,
3764 goal: SelectionGoal::None,
3765 });
3766 to_unfold.push(selection.start..selection.end);
3767 }
3768 }
3769 self.unfold_ranges(to_unfold, cx);
3770 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3771 }
3772
3773 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
3774 self.add_selection(true, cx);
3775 }
3776
3777 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
3778 self.add_selection(false, cx);
3779 }
3780
3781 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
3782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3783 let mut selections = self.local_selections::<Point>(cx);
3784 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
3785 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
3786 let range = oldest_selection.display_range(&display_map).sorted();
3787 let columns = cmp::min(range.start.column(), range.end.column())
3788 ..cmp::max(range.start.column(), range.end.column());
3789
3790 selections.clear();
3791 let mut stack = Vec::new();
3792 for row in range.start.row()..=range.end.row() {
3793 if let Some(selection) = self.build_columnar_selection(
3794 &display_map,
3795 row,
3796 &columns,
3797 oldest_selection.reversed,
3798 ) {
3799 stack.push(selection.id);
3800 selections.push(selection);
3801 }
3802 }
3803
3804 if above {
3805 stack.reverse();
3806 }
3807
3808 AddSelectionsState { above, stack }
3809 });
3810
3811 let last_added_selection = *state.stack.last().unwrap();
3812 let mut new_selections = Vec::new();
3813 if above == state.above {
3814 let end_row = if above {
3815 0
3816 } else {
3817 display_map.max_point().row()
3818 };
3819
3820 'outer: for selection in selections {
3821 if selection.id == last_added_selection {
3822 let range = selection.display_range(&display_map).sorted();
3823 debug_assert_eq!(range.start.row(), range.end.row());
3824 let mut row = range.start.row();
3825 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
3826 {
3827 start..end
3828 } else {
3829 cmp::min(range.start.column(), range.end.column())
3830 ..cmp::max(range.start.column(), range.end.column())
3831 };
3832
3833 while row != end_row {
3834 if above {
3835 row -= 1;
3836 } else {
3837 row += 1;
3838 }
3839
3840 if let Some(new_selection) = self.build_columnar_selection(
3841 &display_map,
3842 row,
3843 &columns,
3844 selection.reversed,
3845 ) {
3846 state.stack.push(new_selection.id);
3847 if above {
3848 new_selections.push(new_selection);
3849 new_selections.push(selection);
3850 } else {
3851 new_selections.push(selection);
3852 new_selections.push(new_selection);
3853 }
3854
3855 continue 'outer;
3856 }
3857 }
3858 }
3859
3860 new_selections.push(selection);
3861 }
3862 } else {
3863 new_selections = selections;
3864 new_selections.retain(|s| s.id != last_added_selection);
3865 state.stack.pop();
3866 }
3867
3868 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3869 if state.stack.len() > 1 {
3870 self.add_selections_state = Some(state);
3871 }
3872 }
3873
3874 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
3875 let replace_newest = action.0;
3876 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3877 let buffer = &display_map.buffer_snapshot;
3878 let mut selections = self.local_selections::<usize>(cx);
3879 if let Some(mut select_next_state) = self.select_next_state.take() {
3880 let query = &select_next_state.query;
3881 if !select_next_state.done {
3882 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
3883 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
3884 let mut next_selected_range = None;
3885
3886 let bytes_after_last_selection =
3887 buffer.bytes_in_range(last_selection.end..buffer.len());
3888 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
3889 let query_matches = query
3890 .stream_find_iter(bytes_after_last_selection)
3891 .map(|result| (last_selection.end, result))
3892 .chain(
3893 query
3894 .stream_find_iter(bytes_before_first_selection)
3895 .map(|result| (0, result)),
3896 );
3897 for (start_offset, query_match) in query_matches {
3898 let query_match = query_match.unwrap(); // can only fail due to I/O
3899 let offset_range =
3900 start_offset + query_match.start()..start_offset + query_match.end();
3901 let display_range = offset_range.start.to_display_point(&display_map)
3902 ..offset_range.end.to_display_point(&display_map);
3903
3904 if !select_next_state.wordwise
3905 || (!movement::is_inside_word(&display_map, display_range.start)
3906 && !movement::is_inside_word(&display_map, display_range.end))
3907 {
3908 next_selected_range = Some(offset_range);
3909 break;
3910 }
3911 }
3912
3913 if let Some(next_selected_range) = next_selected_range {
3914 if replace_newest {
3915 if let Some(newest_id) =
3916 selections.iter().max_by_key(|s| s.id).map(|s| s.id)
3917 {
3918 selections.retain(|s| s.id != newest_id);
3919 }
3920 }
3921 selections.push(Selection {
3922 id: post_inc(&mut self.next_selection_id),
3923 start: next_selected_range.start,
3924 end: next_selected_range.end,
3925 reversed: false,
3926 goal: SelectionGoal::None,
3927 });
3928 self.update_selections(selections, Some(Autoscroll::Newest), cx);
3929 } else {
3930 select_next_state.done = true;
3931 }
3932 }
3933
3934 self.select_next_state = Some(select_next_state);
3935 } else if selections.len() == 1 {
3936 let selection = selections.last_mut().unwrap();
3937 if selection.start == selection.end {
3938 let word_range = movement::surrounding_word(
3939 &display_map,
3940 selection.start.to_display_point(&display_map),
3941 );
3942 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
3943 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
3944 selection.goal = SelectionGoal::None;
3945 selection.reversed = false;
3946
3947 let query = buffer
3948 .text_for_range(selection.start..selection.end)
3949 .collect::<String>();
3950 let select_state = SelectNextState {
3951 query: AhoCorasick::new_auto_configured(&[query]),
3952 wordwise: true,
3953 done: false,
3954 };
3955 self.update_selections(selections, Some(Autoscroll::Newest), cx);
3956 self.select_next_state = Some(select_state);
3957 } else {
3958 let query = buffer
3959 .text_for_range(selection.start..selection.end)
3960 .collect::<String>();
3961 self.select_next_state = Some(SelectNextState {
3962 query: AhoCorasick::new_auto_configured(&[query]),
3963 wordwise: false,
3964 done: false,
3965 });
3966 self.select_next(action, cx);
3967 }
3968 }
3969 }
3970
3971 pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
3972 // Get the line comment prefix. Split its trailing whitespace into a separate string,
3973 // as that portion won't be used for detecting if a line is a comment.
3974 let full_comment_prefix =
3975 if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
3976 prefix.to_string()
3977 } else {
3978 return;
3979 };
3980 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
3981 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
3982
3983 self.transact(cx, |this, cx| {
3984 let mut selections = this.local_selections::<Point>(cx);
3985 let mut all_selection_lines_are_comments = true;
3986 let mut edit_ranges = Vec::new();
3987 let mut last_toggled_row = None;
3988 this.buffer.update(cx, |buffer, cx| {
3989 for selection in &mut selections {
3990 edit_ranges.clear();
3991 let snapshot = buffer.snapshot(cx);
3992
3993 let end_row =
3994 if selection.end.row > selection.start.row && selection.end.column == 0 {
3995 selection.end.row
3996 } else {
3997 selection.end.row + 1
3998 };
3999
4000 for row in selection.start.row..end_row {
4001 // If multiple selections contain a given row, avoid processing that
4002 // row more than once.
4003 if last_toggled_row == Some(row) {
4004 continue;
4005 } else {
4006 last_toggled_row = Some(row);
4007 }
4008
4009 if snapshot.is_line_blank(row) {
4010 continue;
4011 }
4012
4013 let start = Point::new(row, snapshot.indent_column_for_line(row));
4014 let mut line_bytes = snapshot
4015 .bytes_in_range(start..snapshot.max_point())
4016 .flatten()
4017 .copied();
4018
4019 // If this line currently begins with the line comment prefix, then record
4020 // the range containing the prefix.
4021 if all_selection_lines_are_comments
4022 && line_bytes
4023 .by_ref()
4024 .take(comment_prefix.len())
4025 .eq(comment_prefix.bytes())
4026 {
4027 // Include any whitespace that matches the comment prefix.
4028 let matching_whitespace_len = line_bytes
4029 .zip(comment_prefix_whitespace.bytes())
4030 .take_while(|(a, b)| a == b)
4031 .count()
4032 as u32;
4033 let end = Point::new(
4034 row,
4035 start.column
4036 + comment_prefix.len() as u32
4037 + matching_whitespace_len,
4038 );
4039 edit_ranges.push(start..end);
4040 }
4041 // If this line does not begin with the line comment prefix, then record
4042 // the position where the prefix should be inserted.
4043 else {
4044 all_selection_lines_are_comments = false;
4045 edit_ranges.push(start..start);
4046 }
4047 }
4048
4049 if !edit_ranges.is_empty() {
4050 if all_selection_lines_are_comments {
4051 buffer.edit(edit_ranges.iter().cloned(), "", cx);
4052 } else {
4053 let min_column =
4054 edit_ranges.iter().map(|r| r.start.column).min().unwrap();
4055 let edit_ranges = edit_ranges.iter().map(|range| {
4056 let position = Point::new(range.start.row, min_column);
4057 position..position
4058 });
4059 buffer.edit(edit_ranges, &full_comment_prefix, cx);
4060 }
4061 }
4062 }
4063 });
4064
4065 this.update_selections(
4066 this.local_selections::<usize>(cx),
4067 Some(Autoscroll::Fit),
4068 cx,
4069 );
4070 });
4071 }
4072
4073 pub fn select_larger_syntax_node(
4074 &mut self,
4075 _: &SelectLargerSyntaxNode,
4076 cx: &mut ViewContext<Self>,
4077 ) {
4078 let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
4079 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4080 let buffer = self.buffer.read(cx).snapshot(cx);
4081
4082 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4083 let mut selected_larger_node = false;
4084 let new_selections = old_selections
4085 .iter()
4086 .map(|selection| {
4087 let old_range = selection.start..selection.end;
4088 let mut new_range = old_range.clone();
4089 while let Some(containing_range) =
4090 buffer.range_for_syntax_ancestor(new_range.clone())
4091 {
4092 new_range = containing_range;
4093 if !display_map.intersects_fold(new_range.start)
4094 && !display_map.intersects_fold(new_range.end)
4095 {
4096 break;
4097 }
4098 }
4099
4100 selected_larger_node |= new_range != old_range;
4101 Selection {
4102 id: selection.id,
4103 start: new_range.start,
4104 end: new_range.end,
4105 goal: SelectionGoal::None,
4106 reversed: selection.reversed,
4107 }
4108 })
4109 .collect::<Vec<_>>();
4110
4111 if selected_larger_node {
4112 stack.push(old_selections);
4113 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4114 }
4115 self.select_larger_syntax_node_stack = stack;
4116 }
4117
4118 pub fn select_smaller_syntax_node(
4119 &mut self,
4120 _: &SelectSmallerSyntaxNode,
4121 cx: &mut ViewContext<Self>,
4122 ) {
4123 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
4124 if let Some(selections) = stack.pop() {
4125 self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
4126 }
4127 self.select_larger_syntax_node_stack = stack;
4128 }
4129
4130 pub fn move_to_enclosing_bracket(
4131 &mut self,
4132 _: &MoveToEnclosingBracket,
4133 cx: &mut ViewContext<Self>,
4134 ) {
4135 let mut selections = self.local_selections::<usize>(cx);
4136 let buffer = self.buffer.read(cx).snapshot(cx);
4137 for selection in &mut selections {
4138 if let Some((open_range, close_range)) =
4139 buffer.enclosing_bracket_ranges(selection.start..selection.end)
4140 {
4141 let close_range = close_range.to_inclusive();
4142 let destination = if close_range.contains(&selection.start)
4143 && close_range.contains(&selection.end)
4144 {
4145 open_range.end
4146 } else {
4147 *close_range.start()
4148 };
4149 selection.start = destination;
4150 selection.end = destination;
4151 }
4152 }
4153
4154 self.update_selections(selections, Some(Autoscroll::Fit), cx);
4155 }
4156
4157 pub fn go_to_diagnostic(
4158 &mut self,
4159 &GoToDiagnostic(direction): &GoToDiagnostic,
4160 cx: &mut ViewContext<Self>,
4161 ) {
4162 let buffer = self.buffer.read(cx).snapshot(cx);
4163 let selection = self.newest_selection_with_snapshot::<usize>(&buffer);
4164 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
4165 active_diagnostics
4166 .primary_range
4167 .to_offset(&buffer)
4168 .to_inclusive()
4169 });
4170 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
4171 if active_primary_range.contains(&selection.head()) {
4172 *active_primary_range.end()
4173 } else {
4174 selection.head()
4175 }
4176 } else {
4177 selection.head()
4178 };
4179
4180 loop {
4181 let mut diagnostics = if direction == Direction::Prev {
4182 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
4183 } else {
4184 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
4185 };
4186 let group = diagnostics.find_map(|entry| {
4187 if entry.diagnostic.is_primary
4188 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
4189 && !entry.range.is_empty()
4190 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
4191 {
4192 Some((entry.range, entry.diagnostic.group_id))
4193 } else {
4194 None
4195 }
4196 });
4197
4198 if let Some((primary_range, group_id)) = group {
4199 self.activate_diagnostics(group_id, cx);
4200 self.update_selections(
4201 vec![Selection {
4202 id: selection.id,
4203 start: primary_range.start,
4204 end: primary_range.start,
4205 reversed: false,
4206 goal: SelectionGoal::None,
4207 }],
4208 Some(Autoscroll::Center),
4209 cx,
4210 );
4211 break;
4212 } else {
4213 // Cycle around to the start of the buffer, potentially moving back to the start of
4214 // the currently active diagnostic.
4215 active_primary_range.take();
4216 if direction == Direction::Prev {
4217 if search_start == buffer.len() {
4218 break;
4219 } else {
4220 search_start = buffer.len();
4221 }
4222 } else {
4223 if search_start == 0 {
4224 break;
4225 } else {
4226 search_start = 0;
4227 }
4228 }
4229 }
4230 }
4231 }
4232
4233 pub fn go_to_definition(
4234 workspace: &mut Workspace,
4235 _: &GoToDefinition,
4236 cx: &mut ViewContext<Workspace>,
4237 ) {
4238 let active_item = workspace.active_item(cx);
4239 let editor_handle = if let Some(editor) = active_item
4240 .as_ref()
4241 .and_then(|item| item.act_as::<Self>(cx))
4242 {
4243 editor
4244 } else {
4245 return;
4246 };
4247
4248 let editor = editor_handle.read(cx);
4249 let head = editor.newest_selection::<usize>(cx).head();
4250 let (buffer, head) =
4251 if let Some(text_anchor) = editor.buffer.read(cx).text_anchor_for_position(head, cx) {
4252 text_anchor
4253 } else {
4254 return;
4255 };
4256
4257 let project = workspace.project().clone();
4258 let definitions = project.update(cx, |project, cx| project.definition(&buffer, head, cx));
4259 cx.spawn(|workspace, mut cx| async move {
4260 let definitions = definitions.await?;
4261 workspace.update(&mut cx, |workspace, cx| {
4262 let nav_history = workspace.active_pane().read(cx).nav_history().clone();
4263 for definition in definitions {
4264 let range = definition.range.to_offset(definition.buffer.read(cx));
4265
4266 let target_editor_handle = workspace.open_project_item(definition.buffer, cx);
4267 target_editor_handle.update(cx, |target_editor, cx| {
4268 // When selecting a definition in a different buffer, disable the nav history
4269 // to avoid creating a history entry at the previous cursor location.
4270 if editor_handle != target_editor_handle {
4271 nav_history.borrow_mut().disable();
4272 }
4273 target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
4274 nav_history.borrow_mut().enable();
4275 });
4276 }
4277 });
4278
4279 Ok::<(), anyhow::Error>(())
4280 })
4281 .detach_and_log_err(cx);
4282 }
4283
4284 pub fn find_all_references(
4285 workspace: &mut Workspace,
4286 _: &FindAllReferences,
4287 cx: &mut ViewContext<Workspace>,
4288 ) -> Option<Task<Result<()>>> {
4289 let active_item = workspace.active_item(cx)?;
4290 let editor_handle = active_item.act_as::<Self>(cx)?;
4291
4292 let editor = editor_handle.read(cx);
4293 let head = editor.newest_selection::<usize>(cx).head();
4294 let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx)?;
4295 let replica_id = editor.replica_id(cx);
4296
4297 let project = workspace.project().clone();
4298 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
4299 Some(cx.spawn(|workspace, mut cx| async move {
4300 let mut locations = references.await?;
4301 if locations.is_empty() {
4302 return Ok(());
4303 }
4304
4305 locations.sort_by_key(|location| location.buffer.id());
4306 let mut locations = locations.into_iter().peekable();
4307 let mut ranges_to_highlight = Vec::new();
4308
4309 let excerpt_buffer = cx.add_model(|cx| {
4310 let mut symbol_name = None;
4311 let mut multibuffer = MultiBuffer::new(replica_id);
4312 while let Some(location) = locations.next() {
4313 let buffer = location.buffer.read(cx);
4314 let mut ranges_for_buffer = Vec::new();
4315 let range = location.range.to_offset(buffer);
4316 ranges_for_buffer.push(range.clone());
4317 if symbol_name.is_none() {
4318 symbol_name = Some(buffer.text_for_range(range).collect::<String>());
4319 }
4320
4321 while let Some(next_location) = locations.peek() {
4322 if next_location.buffer == location.buffer {
4323 ranges_for_buffer.push(next_location.range.to_offset(buffer));
4324 locations.next();
4325 } else {
4326 break;
4327 }
4328 }
4329
4330 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
4331 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
4332 location.buffer.clone(),
4333 ranges_for_buffer,
4334 1,
4335 cx,
4336 ));
4337 }
4338 multibuffer.with_title(format!("References to `{}`", symbol_name.unwrap()))
4339 });
4340
4341 workspace.update(&mut cx, |workspace, cx| {
4342 let editor =
4343 cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
4344 editor.update(cx, |editor, cx| {
4345 let color = editor.style(cx).highlighted_line_background;
4346 editor.highlight_background::<Self>(ranges_to_highlight, color, cx);
4347 });
4348 workspace.add_item(Box::new(editor), cx);
4349 });
4350
4351 Ok(())
4352 }))
4353 }
4354
4355 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
4356 use language::ToOffset as _;
4357
4358 let project = self.project.clone()?;
4359 let selection = self.newest_anchor_selection().clone();
4360 let (cursor_buffer, cursor_buffer_position) = self
4361 .buffer
4362 .read(cx)
4363 .text_anchor_for_position(selection.head(), cx)?;
4364 let (tail_buffer, _) = self
4365 .buffer
4366 .read(cx)
4367 .text_anchor_for_position(selection.tail(), cx)?;
4368 if tail_buffer != cursor_buffer {
4369 return None;
4370 }
4371
4372 let snapshot = cursor_buffer.read(cx).snapshot();
4373 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
4374 let prepare_rename = project.update(cx, |project, cx| {
4375 project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
4376 });
4377
4378 Some(cx.spawn(|this, mut cx| async move {
4379 if let Some(rename_range) = prepare_rename.await? {
4380 let rename_buffer_range = rename_range.to_offset(&snapshot);
4381 let cursor_offset_in_rename_range =
4382 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
4383
4384 this.update(&mut cx, |this, cx| {
4385 this.take_rename(false, cx);
4386 let style = this.style(cx);
4387 let buffer = this.buffer.read(cx).read(cx);
4388 let cursor_offset = selection.head().to_offset(&buffer);
4389 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
4390 let rename_end = rename_start + rename_buffer_range.len();
4391 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
4392 let mut old_highlight_id = None;
4393 let old_name = buffer
4394 .chunks(rename_start..rename_end, true)
4395 .map(|chunk| {
4396 if old_highlight_id.is_none() {
4397 old_highlight_id = chunk.syntax_highlight_id;
4398 }
4399 chunk.text
4400 })
4401 .collect();
4402
4403 drop(buffer);
4404
4405 // Position the selection in the rename editor so that it matches the current selection.
4406 this.show_local_selections = false;
4407 let rename_editor = cx.add_view(|cx| {
4408 let mut editor = Editor::single_line(None, cx);
4409 if let Some(old_highlight_id) = old_highlight_id {
4410 editor.override_text_style =
4411 Some(Box::new(move |style| old_highlight_id.style(&style.syntax)));
4412 }
4413 editor
4414 .buffer
4415 .update(cx, |buffer, cx| buffer.edit([0..0], &old_name, cx));
4416 editor.select_all(&SelectAll, cx);
4417 editor
4418 });
4419
4420 let ranges = this
4421 .clear_background_highlights::<DocumentHighlightWrite>(cx)
4422 .into_iter()
4423 .flat_map(|(_, ranges)| ranges)
4424 .chain(
4425 this.clear_background_highlights::<DocumentHighlightRead>(cx)
4426 .into_iter()
4427 .flat_map(|(_, ranges)| ranges),
4428 )
4429 .collect();
4430
4431 this.highlight_text::<Rename>(
4432 ranges,
4433 HighlightStyle {
4434 fade_out: Some(style.rename_fade),
4435 ..Default::default()
4436 },
4437 cx,
4438 );
4439 cx.focus(&rename_editor);
4440 let block_id = this.insert_blocks(
4441 [BlockProperties {
4442 position: range.start.clone(),
4443 height: 1,
4444 render: Arc::new({
4445 let editor = rename_editor.clone();
4446 move |cx: &BlockContext| {
4447 ChildView::new(editor.clone())
4448 .contained()
4449 .with_padding_left(cx.anchor_x)
4450 .boxed()
4451 }
4452 }),
4453 disposition: BlockDisposition::Below,
4454 }],
4455 cx,
4456 )[0];
4457 this.pending_rename = Some(RenameState {
4458 range,
4459 old_name,
4460 editor: rename_editor,
4461 block_id,
4462 });
4463 });
4464 }
4465
4466 Ok(())
4467 }))
4468 }
4469
4470 pub fn confirm_rename(
4471 workspace: &mut Workspace,
4472 _: &ConfirmRename,
4473 cx: &mut ViewContext<Workspace>,
4474 ) -> Option<Task<Result<()>>> {
4475 let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
4476
4477 let (buffer, range, old_name, new_name) = editor.update(cx, |editor, cx| {
4478 let rename = editor.take_rename(false, cx)?;
4479 let buffer = editor.buffer.read(cx);
4480 let (start_buffer, start) =
4481 buffer.text_anchor_for_position(rename.range.start.clone(), cx)?;
4482 let (end_buffer, end) =
4483 buffer.text_anchor_for_position(rename.range.end.clone(), cx)?;
4484 if start_buffer == end_buffer {
4485 let new_name = rename.editor.read(cx).text(cx);
4486 Some((start_buffer, start..end, rename.old_name, new_name))
4487 } else {
4488 None
4489 }
4490 })?;
4491
4492 let rename = workspace.project().clone().update(cx, |project, cx| {
4493 project.perform_rename(
4494 buffer.clone(),
4495 range.start.clone(),
4496 new_name.clone(),
4497 true,
4498 cx,
4499 )
4500 });
4501
4502 Some(cx.spawn(|workspace, mut cx| async move {
4503 let project_transaction = rename.await?;
4504 Self::open_project_transaction(
4505 editor.clone(),
4506 workspace,
4507 project_transaction,
4508 format!("Rename: {} → {}", old_name, new_name),
4509 cx.clone(),
4510 )
4511 .await?;
4512
4513 editor.update(&mut cx, |editor, cx| {
4514 editor.refresh_document_highlights(cx);
4515 });
4516 Ok(())
4517 }))
4518 }
4519
4520 fn take_rename(
4521 &mut self,
4522 moving_cursor: bool,
4523 cx: &mut ViewContext<Self>,
4524 ) -> Option<RenameState> {
4525 let rename = self.pending_rename.take()?;
4526 self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4527 self.clear_text_highlights::<Rename>(cx);
4528 self.show_local_selections = true;
4529
4530 if moving_cursor {
4531 let cursor_in_rename_editor =
4532 rename.editor.read(cx).newest_selection::<usize>(cx).head();
4533
4534 // Update the selection to match the position of the selection inside
4535 // the rename editor.
4536 let snapshot = self.buffer.read(cx).read(cx);
4537 let rename_range = rename.range.to_offset(&snapshot);
4538 let cursor_in_editor = snapshot
4539 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
4540 .min(rename_range.end);
4541 drop(snapshot);
4542
4543 self.update_selections(
4544 vec![Selection {
4545 id: self.newest_anchor_selection().id,
4546 start: cursor_in_editor,
4547 end: cursor_in_editor,
4548 reversed: false,
4549 goal: SelectionGoal::None,
4550 }],
4551 None,
4552 cx,
4553 );
4554 }
4555
4556 Some(rename)
4557 }
4558
4559 fn invalidate_rename_range(
4560 &mut self,
4561 buffer: &MultiBufferSnapshot,
4562 cx: &mut ViewContext<Self>,
4563 ) {
4564 if let Some(rename) = self.pending_rename.as_ref() {
4565 if self.selections.len() == 1 {
4566 let head = self.selections[0].head().to_offset(buffer);
4567 let range = rename.range.to_offset(buffer).to_inclusive();
4568 if range.contains(&head) {
4569 return;
4570 }
4571 }
4572 let rename = self.pending_rename.take().unwrap();
4573 self.remove_blocks([rename.block_id].into_iter().collect(), cx);
4574 self.clear_background_highlights::<Rename>(cx);
4575 }
4576 }
4577
4578 #[cfg(any(test, feature = "test-support"))]
4579 pub fn pending_rename(&self) -> Option<&RenameState> {
4580 self.pending_rename.as_ref()
4581 }
4582
4583 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
4584 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
4585 let buffer = self.buffer.read(cx).snapshot(cx);
4586 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
4587 let is_valid = buffer
4588 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
4589 .any(|entry| {
4590 entry.diagnostic.is_primary
4591 && !entry.range.is_empty()
4592 && entry.range.start == primary_range_start
4593 && entry.diagnostic.message == active_diagnostics.primary_message
4594 });
4595
4596 if is_valid != active_diagnostics.is_valid {
4597 active_diagnostics.is_valid = is_valid;
4598 let mut new_styles = HashMap::default();
4599 for (block_id, diagnostic) in &active_diagnostics.blocks {
4600 new_styles.insert(
4601 *block_id,
4602 diagnostic_block_renderer(diagnostic.clone(), is_valid),
4603 );
4604 }
4605 self.display_map
4606 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
4607 }
4608 }
4609 }
4610
4611 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
4612 self.dismiss_diagnostics(cx);
4613 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
4614 let buffer = self.buffer.read(cx).snapshot(cx);
4615
4616 let mut primary_range = None;
4617 let mut primary_message = None;
4618 let mut group_end = Point::zero();
4619 let diagnostic_group = buffer
4620 .diagnostic_group::<Point>(group_id)
4621 .map(|entry| {
4622 if entry.range.end > group_end {
4623 group_end = entry.range.end;
4624 }
4625 if entry.diagnostic.is_primary {
4626 primary_range = Some(entry.range.clone());
4627 primary_message = Some(entry.diagnostic.message.clone());
4628 }
4629 entry
4630 })
4631 .collect::<Vec<_>>();
4632 let primary_range = primary_range.unwrap();
4633 let primary_message = primary_message.unwrap();
4634 let primary_range =
4635 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
4636
4637 let blocks = display_map
4638 .insert_blocks(
4639 diagnostic_group.iter().map(|entry| {
4640 let diagnostic = entry.diagnostic.clone();
4641 let message_height = diagnostic.message.lines().count() as u8;
4642 BlockProperties {
4643 position: buffer.anchor_after(entry.range.start),
4644 height: message_height,
4645 render: diagnostic_block_renderer(diagnostic, true),
4646 disposition: BlockDisposition::Below,
4647 }
4648 }),
4649 cx,
4650 )
4651 .into_iter()
4652 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
4653 .collect();
4654
4655 Some(ActiveDiagnosticGroup {
4656 primary_range,
4657 primary_message,
4658 blocks,
4659 is_valid: true,
4660 })
4661 });
4662 }
4663
4664 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
4665 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
4666 self.display_map.update(cx, |display_map, cx| {
4667 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
4668 });
4669 cx.notify();
4670 }
4671 }
4672
4673 fn build_columnar_selection(
4674 &mut self,
4675 display_map: &DisplaySnapshot,
4676 row: u32,
4677 columns: &Range<u32>,
4678 reversed: bool,
4679 ) -> Option<Selection<Point>> {
4680 let is_empty = columns.start == columns.end;
4681 let line_len = display_map.line_len(row);
4682 if columns.start < line_len || (is_empty && columns.start == line_len) {
4683 let start = DisplayPoint::new(row, columns.start);
4684 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
4685 Some(Selection {
4686 id: post_inc(&mut self.next_selection_id),
4687 start: start.to_point(display_map),
4688 end: end.to_point(display_map),
4689 reversed,
4690 goal: SelectionGoal::ColumnRange {
4691 start: columns.start,
4692 end: columns.end,
4693 },
4694 })
4695 } else {
4696 None
4697 }
4698 }
4699
4700 pub fn local_selections_in_range(
4701 &self,
4702 range: Range<Anchor>,
4703 display_map: &DisplaySnapshot,
4704 ) -> Vec<Selection<Point>> {
4705 let buffer = &display_map.buffer_snapshot;
4706
4707 let start_ix = match self
4708 .selections
4709 .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer))
4710 {
4711 Ok(ix) | Err(ix) => ix,
4712 };
4713 let end_ix = match self
4714 .selections
4715 .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer))
4716 {
4717 Ok(ix) => ix + 1,
4718 Err(ix) => ix,
4719 };
4720
4721 fn point_selection(
4722 selection: &Selection<Anchor>,
4723 buffer: &MultiBufferSnapshot,
4724 ) -> Selection<Point> {
4725 let start = selection.start.to_point(&buffer);
4726 let end = selection.end.to_point(&buffer);
4727 Selection {
4728 id: selection.id,
4729 start,
4730 end,
4731 reversed: selection.reversed,
4732 goal: selection.goal,
4733 }
4734 }
4735
4736 self.selections[start_ix..end_ix]
4737 .iter()
4738 .chain(
4739 self.pending_selection
4740 .as_ref()
4741 .map(|pending| &pending.selection),
4742 )
4743 .map(|s| point_selection(s, &buffer))
4744 .collect()
4745 }
4746
4747 pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
4748 where
4749 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
4750 {
4751 let buffer = self.buffer.read(cx).snapshot(cx);
4752 let mut selections = self
4753 .resolve_selections::<D, _>(self.selections.iter(), &buffer)
4754 .peekable();
4755
4756 let mut pending_selection = self.pending_selection::<D>(&buffer);
4757
4758 iter::from_fn(move || {
4759 if let Some(pending) = pending_selection.as_mut() {
4760 while let Some(next_selection) = selections.peek() {
4761 if pending.start <= next_selection.end && pending.end >= next_selection.start {
4762 let next_selection = selections.next().unwrap();
4763 if next_selection.start < pending.start {
4764 pending.start = next_selection.start;
4765 }
4766 if next_selection.end > pending.end {
4767 pending.end = next_selection.end;
4768 }
4769 } else if next_selection.end < pending.start {
4770 return selections.next();
4771 } else {
4772 break;
4773 }
4774 }
4775
4776 pending_selection.take()
4777 } else {
4778 selections.next()
4779 }
4780 })
4781 .collect()
4782 }
4783
4784 fn resolve_selections<'a, D, I>(
4785 &self,
4786 selections: I,
4787 snapshot: &MultiBufferSnapshot,
4788 ) -> impl 'a + Iterator<Item = Selection<D>>
4789 where
4790 D: TextDimension + Ord + Sub<D, Output = D>,
4791 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
4792 {
4793 let (to_summarize, selections) = selections.into_iter().tee();
4794 let mut summaries = snapshot
4795 .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
4796 .into_iter();
4797 selections.map(move |s| Selection {
4798 id: s.id,
4799 start: summaries.next().unwrap(),
4800 end: summaries.next().unwrap(),
4801 reversed: s.reversed,
4802 goal: s.goal,
4803 })
4804 }
4805
4806 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4807 &self,
4808 snapshot: &MultiBufferSnapshot,
4809 ) -> Option<Selection<D>> {
4810 self.pending_selection
4811 .as_ref()
4812 .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
4813 }
4814
4815 fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4816 &self,
4817 selection: &Selection<Anchor>,
4818 buffer: &MultiBufferSnapshot,
4819 ) -> Selection<D> {
4820 Selection {
4821 id: selection.id,
4822 start: selection.start.summary::<D>(&buffer),
4823 end: selection.end.summary::<D>(&buffer),
4824 reversed: selection.reversed,
4825 goal: selection.goal,
4826 }
4827 }
4828
4829 fn selection_count<'a>(&self) -> usize {
4830 let mut count = self.selections.len();
4831 if self.pending_selection.is_some() {
4832 count += 1;
4833 }
4834 count
4835 }
4836
4837 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4838 &self,
4839 cx: &AppContext,
4840 ) -> Selection<D> {
4841 let snapshot = self.buffer.read(cx).read(cx);
4842 self.selections
4843 .iter()
4844 .min_by_key(|s| s.id)
4845 .map(|selection| self.resolve_selection(selection, &snapshot))
4846 .or_else(|| self.pending_selection(&snapshot))
4847 .unwrap()
4848 }
4849
4850 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4851 &self,
4852 cx: &AppContext,
4853 ) -> Selection<D> {
4854 self.resolve_selection(
4855 self.newest_anchor_selection(),
4856 &self.buffer.read(cx).read(cx),
4857 )
4858 }
4859
4860 pub fn newest_selection_with_snapshot<D: TextDimension + Ord + Sub<D, Output = D>>(
4861 &self,
4862 snapshot: &MultiBufferSnapshot,
4863 ) -> Selection<D> {
4864 self.resolve_selection(self.newest_anchor_selection(), snapshot)
4865 }
4866
4867 pub fn newest_anchor_selection(&self) -> &Selection<Anchor> {
4868 self.pending_selection
4869 .as_ref()
4870 .map(|s| &s.selection)
4871 .or_else(|| self.selections.iter().max_by_key(|s| s.id))
4872 .unwrap()
4873 }
4874
4875 pub fn update_selections<T>(
4876 &mut self,
4877 mut selections: Vec<Selection<T>>,
4878 autoscroll: Option<Autoscroll>,
4879 cx: &mut ViewContext<Self>,
4880 ) where
4881 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
4882 {
4883 let buffer = self.buffer.read(cx).snapshot(cx);
4884 selections.sort_unstable_by_key(|s| s.start);
4885
4886 // Merge overlapping selections.
4887 let mut i = 1;
4888 while i < selections.len() {
4889 if selections[i - 1].end >= selections[i].start {
4890 let removed = selections.remove(i);
4891 if removed.start < selections[i - 1].start {
4892 selections[i - 1].start = removed.start;
4893 }
4894 if removed.end > selections[i - 1].end {
4895 selections[i - 1].end = removed.end;
4896 }
4897 } else {
4898 i += 1;
4899 }
4900 }
4901
4902 if let Some(autoscroll) = autoscroll {
4903 self.request_autoscroll(autoscroll, cx);
4904 }
4905
4906 self.set_selections(
4907 Arc::from_iter(selections.into_iter().map(|selection| {
4908 let end_bias = if selection.end > selection.start {
4909 Bias::Left
4910 } else {
4911 Bias::Right
4912 };
4913 Selection {
4914 id: selection.id,
4915 start: buffer.anchor_after(selection.start),
4916 end: buffer.anchor_at(selection.end, end_bias),
4917 reversed: selection.reversed,
4918 goal: selection.goal,
4919 }
4920 })),
4921 None,
4922 true,
4923 cx,
4924 );
4925 }
4926
4927 pub fn set_selections_from_remote(
4928 &mut self,
4929 mut selections: Vec<Selection<Anchor>>,
4930 cx: &mut ViewContext<Self>,
4931 ) {
4932 let buffer = self.buffer.read(cx);
4933 let buffer = buffer.read(cx);
4934 selections.sort_by(|a, b| {
4935 a.start
4936 .cmp(&b.start, &*buffer)
4937 .then_with(|| b.end.cmp(&a.end, &*buffer))
4938 });
4939
4940 // Merge overlapping selections
4941 let mut i = 1;
4942 while i < selections.len() {
4943 if selections[i - 1]
4944 .end
4945 .cmp(&selections[i].start, &*buffer)
4946 .is_ge()
4947 {
4948 let removed = selections.remove(i);
4949 if removed
4950 .start
4951 .cmp(&selections[i - 1].start, &*buffer)
4952 .is_lt()
4953 {
4954 selections[i - 1].start = removed.start;
4955 }
4956 if removed.end.cmp(&selections[i - 1].end, &*buffer).is_gt() {
4957 selections[i - 1].end = removed.end;
4958 }
4959 } else {
4960 i += 1;
4961 }
4962 }
4963
4964 drop(buffer);
4965 self.set_selections(selections.into(), None, false, cx);
4966 }
4967
4968 /// Compute new ranges for any selections that were located in excerpts that have
4969 /// since been removed.
4970 ///
4971 /// Returns a `HashMap` indicating which selections whose former head position
4972 /// was no longer present. The keys of the map are selection ids. The values are
4973 /// the id of the new excerpt where the head of the selection has been moved.
4974 pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
4975 let snapshot = self.buffer.read(cx).read(cx);
4976 let mut selections_with_lost_position = HashMap::default();
4977
4978 let mut pending_selection = self.pending_selection.take();
4979 if let Some(pending) = pending_selection.as_mut() {
4980 let anchors =
4981 snapshot.refresh_anchors([&pending.selection.start, &pending.selection.end]);
4982 let (_, start, kept_start) = anchors[0].clone();
4983 let (_, end, kept_end) = anchors[1].clone();
4984 let kept_head = if pending.selection.reversed {
4985 kept_start
4986 } else {
4987 kept_end
4988 };
4989 if !kept_head {
4990 selections_with_lost_position.insert(
4991 pending.selection.id,
4992 pending.selection.head().excerpt_id.clone(),
4993 );
4994 }
4995
4996 pending.selection.start = start;
4997 pending.selection.end = end;
4998 }
4999
5000 let anchors_with_status = snapshot.refresh_anchors(
5001 self.selections
5002 .iter()
5003 .flat_map(|selection| [&selection.start, &selection.end]),
5004 );
5005 self.selections = anchors_with_status
5006 .chunks(2)
5007 .map(|selection_anchors| {
5008 let (anchor_ix, start, kept_start) = selection_anchors[0].clone();
5009 let (_, end, kept_end) = selection_anchors[1].clone();
5010 let selection = &self.selections[anchor_ix / 2];
5011 let kept_head = if selection.reversed {
5012 kept_start
5013 } else {
5014 kept_end
5015 };
5016 if !kept_head {
5017 selections_with_lost_position
5018 .insert(selection.id, selection.head().excerpt_id.clone());
5019 }
5020
5021 Selection {
5022 id: selection.id,
5023 start,
5024 end,
5025 reversed: selection.reversed,
5026 goal: selection.goal,
5027 }
5028 })
5029 .collect();
5030 drop(snapshot);
5031
5032 let new_selections = self.local_selections::<usize>(cx);
5033 if !new_selections.is_empty() {
5034 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
5035 }
5036 self.pending_selection = pending_selection;
5037
5038 selections_with_lost_position
5039 }
5040
5041 fn set_selections(
5042 &mut self,
5043 selections: Arc<[Selection<Anchor>]>,
5044 pending_selection: Option<PendingSelection>,
5045 local: bool,
5046 cx: &mut ViewContext<Self>,
5047 ) {
5048 assert!(
5049 !selections.is_empty() || pending_selection.is_some(),
5050 "must have at least one selection"
5051 );
5052
5053 let old_cursor_position = self.newest_anchor_selection().head();
5054
5055 self.selections = selections;
5056 self.pending_selection = pending_selection;
5057 if self.focused && self.leader_replica_id.is_none() {
5058 self.buffer.update(cx, |buffer, cx| {
5059 buffer.set_active_selections(&self.selections, cx)
5060 });
5061 }
5062
5063 let display_map = self
5064 .display_map
5065 .update(cx, |display_map, cx| display_map.snapshot(cx));
5066 let buffer = &display_map.buffer_snapshot;
5067 self.add_selections_state = None;
5068 self.select_next_state = None;
5069 self.select_larger_syntax_node_stack.clear();
5070 self.autoclose_stack.invalidate(&self.selections, &buffer);
5071 self.snippet_stack.invalidate(&self.selections, &buffer);
5072 self.invalidate_rename_range(&buffer, cx);
5073
5074 let new_cursor_position = self.newest_anchor_selection().head();
5075
5076 self.push_to_nav_history(
5077 old_cursor_position.clone(),
5078 Some(new_cursor_position.to_point(&buffer)),
5079 cx,
5080 );
5081
5082 if local {
5083 let completion_menu = match self.context_menu.as_mut() {
5084 Some(ContextMenu::Completions(menu)) => Some(menu),
5085 _ => {
5086 self.context_menu.take();
5087 None
5088 }
5089 };
5090
5091 if let Some(completion_menu) = completion_menu {
5092 let cursor_position = new_cursor_position.to_offset(&buffer);
5093 let (word_range, kind) =
5094 buffer.surrounding_word(completion_menu.initial_position.clone());
5095 if kind == Some(CharKind::Word)
5096 && word_range.to_inclusive().contains(&cursor_position)
5097 {
5098 let query = Self::completion_query(&buffer, cursor_position);
5099 cx.background()
5100 .block(completion_menu.filter(query.as_deref(), cx.background().clone()));
5101 self.show_completions(&ShowCompletions, cx);
5102 } else {
5103 self.hide_context_menu(cx);
5104 }
5105 }
5106
5107 if old_cursor_position.to_display_point(&display_map).row()
5108 != new_cursor_position.to_display_point(&display_map).row()
5109 {
5110 self.available_code_actions.take();
5111 }
5112 self.refresh_code_actions(cx);
5113 self.refresh_document_highlights(cx);
5114 }
5115
5116 self.pause_cursor_blinking(cx);
5117 cx.emit(Event::SelectionsChanged { local });
5118 }
5119
5120 pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5121 self.autoscroll_request = Some((autoscroll, true));
5122 cx.notify();
5123 }
5124
5125 fn request_autoscroll_remotely(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
5126 self.autoscroll_request = Some((autoscroll, false));
5127 cx.notify();
5128 }
5129
5130 pub fn transact(
5131 &mut self,
5132 cx: &mut ViewContext<Self>,
5133 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
5134 ) {
5135 self.start_transaction_at(Instant::now(), cx);
5136 update(self, cx);
5137 self.end_transaction_at(Instant::now(), cx);
5138 }
5139
5140 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5141 self.end_selection(cx);
5142 if let Some(tx_id) = self
5143 .buffer
5144 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
5145 {
5146 self.selection_history
5147 .insert(tx_id, (self.selections.clone(), None));
5148 }
5149 }
5150
5151 fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
5152 if let Some(tx_id) = self
5153 .buffer
5154 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
5155 {
5156 if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
5157 *end_selections = Some(self.selections.clone());
5158 } else {
5159 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
5160 }
5161
5162 cx.emit(Event::Edited);
5163 }
5164 }
5165
5166 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
5167 log::info!("Editor::page_up");
5168 }
5169
5170 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
5171 log::info!("Editor::page_down");
5172 }
5173
5174 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
5175 let mut fold_ranges = Vec::new();
5176
5177 let selections = self.local_selections::<Point>(cx);
5178 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5179 for selection in selections {
5180 let range = selection.display_range(&display_map).sorted();
5181 let buffer_start_row = range.start.to_point(&display_map).row;
5182
5183 for row in (0..=range.end.row()).rev() {
5184 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
5185 let fold_range = self.foldable_range_for_line(&display_map, row);
5186 if fold_range.end.row >= buffer_start_row {
5187 fold_ranges.push(fold_range);
5188 if row <= range.start.row() {
5189 break;
5190 }
5191 }
5192 }
5193 }
5194 }
5195
5196 self.fold_ranges(fold_ranges, cx);
5197 }
5198
5199 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
5200 let selections = self.local_selections::<Point>(cx);
5201 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5202 let buffer = &display_map.buffer_snapshot;
5203 let ranges = selections
5204 .iter()
5205 .map(|s| {
5206 let range = s.display_range(&display_map).sorted();
5207 let mut start = range.start.to_point(&display_map);
5208 let mut end = range.end.to_point(&display_map);
5209 start.column = 0;
5210 end.column = buffer.line_len(end.row);
5211 start..end
5212 })
5213 .collect::<Vec<_>>();
5214 self.unfold_ranges(ranges, cx);
5215 }
5216
5217 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
5218 let max_point = display_map.max_point();
5219 if display_row >= max_point.row() {
5220 false
5221 } else {
5222 let (start_indent, is_blank) = display_map.line_indent(display_row);
5223 if is_blank {
5224 false
5225 } else {
5226 for display_row in display_row + 1..=max_point.row() {
5227 let (indent, is_blank) = display_map.line_indent(display_row);
5228 if !is_blank {
5229 return indent > start_indent;
5230 }
5231 }
5232 false
5233 }
5234 }
5235 }
5236
5237 fn foldable_range_for_line(
5238 &self,
5239 display_map: &DisplaySnapshot,
5240 start_row: u32,
5241 ) -> Range<Point> {
5242 let max_point = display_map.max_point();
5243
5244 let (start_indent, _) = display_map.line_indent(start_row);
5245 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
5246 let mut end = None;
5247 for row in start_row + 1..=max_point.row() {
5248 let (indent, is_blank) = display_map.line_indent(row);
5249 if !is_blank && indent <= start_indent {
5250 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
5251 break;
5252 }
5253 }
5254
5255 let end = end.unwrap_or(max_point);
5256 return start.to_point(display_map)..end.to_point(display_map);
5257 }
5258
5259 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
5260 let selections = self.local_selections::<Point>(cx);
5261 let ranges = selections.into_iter().map(|s| s.start..s.end);
5262 self.fold_ranges(ranges, cx);
5263 }
5264
5265 fn fold_ranges<T: ToOffset>(
5266 &mut self,
5267 ranges: impl IntoIterator<Item = Range<T>>,
5268 cx: &mut ViewContext<Self>,
5269 ) {
5270 let mut ranges = ranges.into_iter().peekable();
5271 if ranges.peek().is_some() {
5272 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
5273 self.request_autoscroll(Autoscroll::Fit, cx);
5274 cx.notify();
5275 }
5276 }
5277
5278 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
5279 if !ranges.is_empty() {
5280 self.display_map
5281 .update(cx, |map, cx| map.unfold(ranges, cx));
5282 self.request_autoscroll(Autoscroll::Fit, cx);
5283 cx.notify();
5284 }
5285 }
5286
5287 pub fn insert_blocks(
5288 &mut self,
5289 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
5290 cx: &mut ViewContext<Self>,
5291 ) -> Vec<BlockId> {
5292 let blocks = self
5293 .display_map
5294 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
5295 self.request_autoscroll(Autoscroll::Fit, cx);
5296 blocks
5297 }
5298
5299 pub fn replace_blocks(
5300 &mut self,
5301 blocks: HashMap<BlockId, RenderBlock>,
5302 cx: &mut ViewContext<Self>,
5303 ) {
5304 self.display_map
5305 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
5306 self.request_autoscroll(Autoscroll::Fit, cx);
5307 }
5308
5309 pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
5310 self.display_map.update(cx, |display_map, cx| {
5311 display_map.remove_blocks(block_ids, cx)
5312 });
5313 }
5314
5315 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
5316 self.display_map
5317 .update(cx, |map, cx| map.snapshot(cx))
5318 .longest_row()
5319 }
5320
5321 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
5322 self.display_map
5323 .update(cx, |map, cx| map.snapshot(cx))
5324 .max_point()
5325 }
5326
5327 pub fn text(&self, cx: &AppContext) -> String {
5328 self.buffer.read(cx).read(cx).text()
5329 }
5330
5331 pub fn set_text(&mut self, text: impl Into<String>, cx: &mut ViewContext<Self>) {
5332 self.transact(cx, |this, cx| {
5333 this.buffer
5334 .read(cx)
5335 .as_singleton()
5336 .expect("you can only call set_text on editors for singleton buffers")
5337 .update(cx, |buffer, cx| buffer.set_text(text, cx));
5338 });
5339 }
5340
5341 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
5342 self.display_map
5343 .update(cx, |map, cx| map.snapshot(cx))
5344 .text()
5345 }
5346
5347 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
5348 let language = self.language(cx);
5349 let settings = cx.global::<Settings>();
5350 let mode = self
5351 .soft_wrap_mode_override
5352 .unwrap_or_else(|| settings.soft_wrap(language));
5353 match mode {
5354 settings::SoftWrap::None => SoftWrap::None,
5355 settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5356 settings::SoftWrap::PreferredLineLength => {
5357 SoftWrap::Column(settings.preferred_line_length(language))
5358 }
5359 }
5360 }
5361
5362 pub fn set_soft_wrap_mode(&mut self, mode: settings::SoftWrap, cx: &mut ViewContext<Self>) {
5363 self.soft_wrap_mode_override = Some(mode);
5364 cx.notify();
5365 }
5366
5367 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
5368 self.display_map
5369 .update(cx, |map, cx| map.set_wrap_width(width, cx))
5370 }
5371
5372 pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
5373 self.highlighted_rows = rows;
5374 }
5375
5376 pub fn highlighted_rows(&self) -> Option<Range<u32>> {
5377 self.highlighted_rows.clone()
5378 }
5379
5380 pub fn highlight_background<T: 'static>(
5381 &mut self,
5382 ranges: Vec<Range<Anchor>>,
5383 color: Color,
5384 cx: &mut ViewContext<Self>,
5385 ) {
5386 self.background_highlights
5387 .insert(TypeId::of::<T>(), (color, ranges));
5388 cx.notify();
5389 }
5390
5391 pub fn clear_background_highlights<T: 'static>(
5392 &mut self,
5393 cx: &mut ViewContext<Self>,
5394 ) -> Option<(Color, Vec<Range<Anchor>>)> {
5395 cx.notify();
5396 self.background_highlights.remove(&TypeId::of::<T>())
5397 }
5398
5399 #[cfg(feature = "test-support")]
5400 pub fn all_background_highlights(
5401 &mut self,
5402 cx: &mut ViewContext<Self>,
5403 ) -> Vec<(Range<DisplayPoint>, Color)> {
5404 let snapshot = self.snapshot(cx);
5405 let buffer = &snapshot.buffer_snapshot;
5406 let start = buffer.anchor_before(0);
5407 let end = buffer.anchor_after(buffer.len());
5408 self.background_highlights_in_range(start..end, &snapshot)
5409 }
5410
5411 pub fn background_highlights_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
5412 self.background_highlights
5413 .get(&TypeId::of::<T>())
5414 .map(|(color, ranges)| (*color, ranges.as_slice()))
5415 }
5416
5417 pub fn background_highlights_in_range(
5418 &self,
5419 search_range: Range<Anchor>,
5420 display_snapshot: &DisplaySnapshot,
5421 ) -> Vec<(Range<DisplayPoint>, Color)> {
5422 let mut results = Vec::new();
5423 let buffer = &display_snapshot.buffer_snapshot;
5424 for (color, ranges) in self.background_highlights.values() {
5425 let start_ix = match ranges.binary_search_by(|probe| {
5426 let cmp = probe.end.cmp(&search_range.start, &buffer);
5427 if cmp.is_gt() {
5428 Ordering::Greater
5429 } else {
5430 Ordering::Less
5431 }
5432 }) {
5433 Ok(i) | Err(i) => i,
5434 };
5435 for range in &ranges[start_ix..] {
5436 if range.start.cmp(&search_range.end, &buffer).is_ge() {
5437 break;
5438 }
5439 let start = range
5440 .start
5441 .to_point(buffer)
5442 .to_display_point(display_snapshot);
5443 let end = range
5444 .end
5445 .to_point(buffer)
5446 .to_display_point(display_snapshot);
5447 results.push((start..end, *color))
5448 }
5449 }
5450 results
5451 }
5452
5453 pub fn highlight_text<T: 'static>(
5454 &mut self,
5455 ranges: Vec<Range<Anchor>>,
5456 style: HighlightStyle,
5457 cx: &mut ViewContext<Self>,
5458 ) {
5459 self.display_map.update(cx, |map, _| {
5460 map.highlight_text(TypeId::of::<T>(), ranges, style)
5461 });
5462 cx.notify();
5463 }
5464
5465 pub fn clear_text_highlights<T: 'static>(
5466 &mut self,
5467 cx: &mut ViewContext<Self>,
5468 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
5469 cx.notify();
5470 self.display_map
5471 .update(cx, |map, _| map.clear_text_highlights(TypeId::of::<T>()))
5472 }
5473
5474 fn next_blink_epoch(&mut self) -> usize {
5475 self.blink_epoch += 1;
5476 self.blink_epoch
5477 }
5478
5479 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
5480 if !self.focused {
5481 return;
5482 }
5483
5484 self.show_local_cursors = true;
5485 cx.notify();
5486
5487 let epoch = self.next_blink_epoch();
5488 cx.spawn(|this, mut cx| {
5489 let this = this.downgrade();
5490 async move {
5491 Timer::after(CURSOR_BLINK_INTERVAL).await;
5492 if let Some(this) = this.upgrade(&cx) {
5493 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
5494 }
5495 }
5496 })
5497 .detach();
5498 }
5499
5500 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5501 if epoch == self.blink_epoch {
5502 self.blinking_paused = false;
5503 self.blink_cursors(epoch, cx);
5504 }
5505 }
5506
5507 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5508 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
5509 self.show_local_cursors = !self.show_local_cursors;
5510 cx.notify();
5511
5512 let epoch = self.next_blink_epoch();
5513 cx.spawn(|this, mut cx| {
5514 let this = this.downgrade();
5515 async move {
5516 Timer::after(CURSOR_BLINK_INTERVAL).await;
5517 if let Some(this) = this.upgrade(&cx) {
5518 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
5519 }
5520 }
5521 })
5522 .detach();
5523 }
5524 }
5525
5526 pub fn show_local_cursors(&self) -> bool {
5527 self.show_local_cursors && self.focused
5528 }
5529
5530 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
5531 cx.notify();
5532 }
5533
5534 fn on_buffer_event(
5535 &mut self,
5536 _: ModelHandle<MultiBuffer>,
5537 event: &language::Event,
5538 cx: &mut ViewContext<Self>,
5539 ) {
5540 match event {
5541 language::Event::Edited => {
5542 self.refresh_active_diagnostics(cx);
5543 self.refresh_code_actions(cx);
5544 cx.emit(Event::BufferEdited);
5545 }
5546 language::Event::Dirtied => cx.emit(Event::Dirtied),
5547 language::Event::Saved => cx.emit(Event::Saved),
5548 language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
5549 language::Event::Reloaded => cx.emit(Event::TitleChanged),
5550 language::Event::Closed => cx.emit(Event::Closed),
5551 language::Event::DiagnosticsUpdated => {
5552 self.refresh_active_diagnostics(cx);
5553 }
5554 _ => {}
5555 }
5556 }
5557
5558 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
5559 cx.notify();
5560 }
5561
5562 pub fn set_searchable(&mut self, searchable: bool) {
5563 self.searchable = searchable;
5564 }
5565
5566 pub fn searchable(&self) -> bool {
5567 self.searchable
5568 }
5569
5570 fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
5571 let active_item = workspace.active_item(cx);
5572 let editor_handle = if let Some(editor) = active_item
5573 .as_ref()
5574 .and_then(|item| item.act_as::<Self>(cx))
5575 {
5576 editor
5577 } else {
5578 cx.propagate_action();
5579 return;
5580 };
5581
5582 let editor = editor_handle.read(cx);
5583 let buffer = editor.buffer.read(cx);
5584 if buffer.is_singleton() {
5585 cx.propagate_action();
5586 return;
5587 }
5588
5589 let mut new_selections_by_buffer = HashMap::default();
5590 for selection in editor.local_selections::<usize>(cx) {
5591 for (buffer, mut range) in
5592 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
5593 {
5594 if selection.reversed {
5595 mem::swap(&mut range.start, &mut range.end);
5596 }
5597 new_selections_by_buffer
5598 .entry(buffer)
5599 .or_insert(Vec::new())
5600 .push(range)
5601 }
5602 }
5603
5604 editor_handle.update(cx, |editor, cx| {
5605 editor.push_to_nav_history(editor.newest_anchor_selection().head(), None, cx);
5606 });
5607 let nav_history = workspace.active_pane().read(cx).nav_history().clone();
5608 nav_history.borrow_mut().disable();
5609
5610 // We defer the pane interaction because we ourselves are a workspace item
5611 // and activating a new item causes the pane to call a method on us reentrantly,
5612 // which panics if we're on the stack.
5613 cx.defer(move |workspace, cx| {
5614 workspace.activate_next_pane(cx);
5615
5616 for (buffer, ranges) in new_selections_by_buffer.into_iter() {
5617 let editor = workspace.open_project_item::<Self>(buffer, cx);
5618 editor.update(cx, |editor, cx| {
5619 editor.select_ranges(ranges, Some(Autoscroll::Newest), cx);
5620 });
5621 }
5622
5623 nav_history.borrow_mut().enable();
5624 });
5625 }
5626}
5627
5628impl EditorSnapshot {
5629 pub fn is_focused(&self) -> bool {
5630 self.is_focused
5631 }
5632
5633 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
5634 self.placeholder_text.as_ref()
5635 }
5636
5637 pub fn scroll_position(&self) -> Vector2F {
5638 compute_scroll_position(
5639 &self.display_snapshot,
5640 self.scroll_position,
5641 &self.scroll_top_anchor,
5642 )
5643 }
5644}
5645
5646impl Deref for EditorSnapshot {
5647 type Target = DisplaySnapshot;
5648
5649 fn deref(&self) -> &Self::Target {
5650 &self.display_snapshot
5651 }
5652}
5653
5654fn compute_scroll_position(
5655 snapshot: &DisplaySnapshot,
5656 mut scroll_position: Vector2F,
5657 scroll_top_anchor: &Anchor,
5658) -> Vector2F {
5659 if *scroll_top_anchor != Anchor::min() {
5660 let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
5661 scroll_position.set_y(scroll_top + scroll_position.y());
5662 } else {
5663 scroll_position.set_y(0.);
5664 }
5665 scroll_position
5666}
5667
5668#[derive(Copy, Clone, Debug, PartialEq, Eq)]
5669pub enum Event {
5670 Activate,
5671 BufferEdited,
5672 Edited,
5673 Blurred,
5674 Dirtied,
5675 Saved,
5676 TitleChanged,
5677 SelectionsChanged { local: bool },
5678 ScrollPositionChanged { local: bool },
5679 Closed,
5680}
5681
5682pub struct EditorFocused(pub ViewHandle<Editor>);
5683pub struct EditorBlurred(pub ViewHandle<Editor>);
5684pub struct EditorReleased(pub WeakViewHandle<Editor>);
5685
5686impl Entity for Editor {
5687 type Event = Event;
5688
5689 fn release(&mut self, cx: &mut MutableAppContext) {
5690 cx.emit_global(EditorReleased(self.handle.clone()));
5691 }
5692}
5693
5694impl View for Editor {
5695 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5696 let style = self.style(cx);
5697 self.display_map.update(cx, |map, cx| {
5698 map.set_font(style.text.font_id, style.text.font_size, cx)
5699 });
5700 EditorElement::new(self.handle.clone(), style.clone(), self.cursor_shape).boxed()
5701 }
5702
5703 fn ui_name() -> &'static str {
5704 "Editor"
5705 }
5706
5707 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
5708 let focused_event = EditorFocused(cx.handle());
5709 cx.emit_global(focused_event);
5710 if let Some(rename) = self.pending_rename.as_ref() {
5711 cx.focus(&rename.editor);
5712 } else {
5713 self.focused = true;
5714 self.blink_cursors(self.blink_epoch, cx);
5715 self.buffer.update(cx, |buffer, cx| {
5716 buffer.finalize_last_transaction(cx);
5717 if self.leader_replica_id.is_none() {
5718 buffer.set_active_selections(&self.selections, cx);
5719 }
5720 });
5721 }
5722 }
5723
5724 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
5725 let blurred_event = EditorBlurred(cx.handle());
5726 cx.emit_global(blurred_event);
5727 self.focused = false;
5728 self.buffer
5729 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
5730 self.hide_context_menu(cx);
5731 cx.emit(Event::Blurred);
5732 cx.notify();
5733 }
5734
5735 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
5736 let mut cx = Self::default_keymap_context();
5737 let mode = match self.mode {
5738 EditorMode::SingleLine => "single_line",
5739 EditorMode::AutoHeight { .. } => "auto_height",
5740 EditorMode::Full => "full",
5741 };
5742 cx.map.insert("mode".into(), mode.into());
5743 if self.pending_rename.is_some() {
5744 cx.set.insert("renaming".into());
5745 }
5746 match self.context_menu.as_ref() {
5747 Some(ContextMenu::Completions(_)) => {
5748 cx.set.insert("showing_completions".into());
5749 }
5750 Some(ContextMenu::CodeActions(_)) => {
5751 cx.set.insert("showing_code_actions".into());
5752 }
5753 None => {}
5754 }
5755 cx
5756 }
5757}
5758
5759fn build_style(
5760 settings: &Settings,
5761 get_field_editor_theme: Option<GetFieldEditorTheme>,
5762 override_text_style: Option<&OverrideTextStyle>,
5763 cx: &AppContext,
5764) -> EditorStyle {
5765 let font_cache = cx.font_cache();
5766
5767 let mut theme = settings.theme.editor.clone();
5768 let mut style = if let Some(get_field_editor_theme) = get_field_editor_theme {
5769 let field_editor_theme = get_field_editor_theme(&settings.theme);
5770 theme.text_color = field_editor_theme.text.color;
5771 theme.selection = field_editor_theme.selection;
5772 theme.background = field_editor_theme
5773 .container
5774 .background_color
5775 .unwrap_or_default();
5776 EditorStyle {
5777 text: field_editor_theme.text,
5778 placeholder_text: field_editor_theme.placeholder_text,
5779 theme,
5780 }
5781 } else {
5782 let font_family_id = settings.buffer_font_family;
5783 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5784 let font_properties = Default::default();
5785 let font_id = font_cache
5786 .select_font(font_family_id, &font_properties)
5787 .unwrap();
5788 let font_size = settings.buffer_font_size;
5789 EditorStyle {
5790 text: TextStyle {
5791 color: settings.theme.editor.text_color,
5792 font_family_name,
5793 font_family_id,
5794 font_id,
5795 font_size,
5796 font_properties,
5797 underline: Default::default(),
5798 },
5799 placeholder_text: None,
5800 theme,
5801 }
5802 };
5803
5804 if let Some(highlight_style) = override_text_style.and_then(|build_style| build_style(&style)) {
5805 if let Some(highlighted) = style
5806 .text
5807 .clone()
5808 .highlight(highlight_style, font_cache)
5809 .log_err()
5810 {
5811 style.text = highlighted;
5812 }
5813 }
5814
5815 style
5816}
5817
5818trait SelectionExt {
5819 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
5820 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
5821 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
5822 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
5823 -> Range<u32>;
5824}
5825
5826impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
5827 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
5828 let start = self.start.to_point(buffer);
5829 let end = self.end.to_point(buffer);
5830 if self.reversed {
5831 end..start
5832 } else {
5833 start..end
5834 }
5835 }
5836
5837 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
5838 let start = self.start.to_offset(buffer);
5839 let end = self.end.to_offset(buffer);
5840 if self.reversed {
5841 end..start
5842 } else {
5843 start..end
5844 }
5845 }
5846
5847 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
5848 let start = self
5849 .start
5850 .to_point(&map.buffer_snapshot)
5851 .to_display_point(map);
5852 let end = self
5853 .end
5854 .to_point(&map.buffer_snapshot)
5855 .to_display_point(map);
5856 if self.reversed {
5857 end..start
5858 } else {
5859 start..end
5860 }
5861 }
5862
5863 fn spanned_rows(
5864 &self,
5865 include_end_if_at_line_start: bool,
5866 map: &DisplaySnapshot,
5867 ) -> Range<u32> {
5868 let start = self.start.to_point(&map.buffer_snapshot);
5869 let mut end = self.end.to_point(&map.buffer_snapshot);
5870 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
5871 end.row -= 1;
5872 }
5873
5874 let buffer_start = map.prev_line_boundary(start).0;
5875 let buffer_end = map.next_line_boundary(end).0;
5876 buffer_start.row..buffer_end.row + 1
5877 }
5878}
5879
5880impl<T: InvalidationRegion> InvalidationStack<T> {
5881 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
5882 where
5883 S: Clone + ToOffset,
5884 {
5885 while let Some(region) = self.last() {
5886 let all_selections_inside_invalidation_ranges =
5887 if selections.len() == region.ranges().len() {
5888 selections
5889 .iter()
5890 .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
5891 .all(|(selection, invalidation_range)| {
5892 let head = selection.head().to_offset(&buffer);
5893 invalidation_range.start <= head && invalidation_range.end >= head
5894 })
5895 } else {
5896 false
5897 };
5898
5899 if all_selections_inside_invalidation_ranges {
5900 break;
5901 } else {
5902 self.pop();
5903 }
5904 }
5905 }
5906}
5907
5908impl<T> Default for InvalidationStack<T> {
5909 fn default() -> Self {
5910 Self(Default::default())
5911 }
5912}
5913
5914impl<T> Deref for InvalidationStack<T> {
5915 type Target = Vec<T>;
5916
5917 fn deref(&self) -> &Self::Target {
5918 &self.0
5919 }
5920}
5921
5922impl<T> DerefMut for InvalidationStack<T> {
5923 fn deref_mut(&mut self) -> &mut Self::Target {
5924 &mut self.0
5925 }
5926}
5927
5928impl InvalidationRegion for BracketPairState {
5929 fn ranges(&self) -> &[Range<Anchor>] {
5930 &self.ranges
5931 }
5932}
5933
5934impl InvalidationRegion for SnippetState {
5935 fn ranges(&self) -> &[Range<Anchor>] {
5936 &self.ranges[self.active_index]
5937 }
5938}
5939
5940impl Deref for EditorStyle {
5941 type Target = theme::Editor;
5942
5943 fn deref(&self) -> &Self::Target {
5944 &self.theme
5945 }
5946}
5947
5948pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
5949 let mut highlighted_lines = Vec::new();
5950 for line in diagnostic.message.lines() {
5951 highlighted_lines.push(highlight_diagnostic_message(line));
5952 }
5953
5954 Arc::new(move |cx: &BlockContext| {
5955 let settings = cx.global::<Settings>();
5956 let theme = &settings.theme.editor;
5957 let style = diagnostic_style(diagnostic.severity, is_valid, theme);
5958 let font_size = (style.text_scale_factor * settings.buffer_font_size).round();
5959 Flex::column()
5960 .with_children(highlighted_lines.iter().map(|(line, highlights)| {
5961 Label::new(
5962 line.clone(),
5963 style.message.clone().with_font_size(font_size),
5964 )
5965 .with_highlights(highlights.clone())
5966 .contained()
5967 .with_margin_left(cx.anchor_x)
5968 .boxed()
5969 }))
5970 .aligned()
5971 .left()
5972 .boxed()
5973 })
5974}
5975
5976pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
5977 let mut message_without_backticks = String::new();
5978 let mut prev_offset = 0;
5979 let mut inside_block = false;
5980 let mut highlights = Vec::new();
5981 for (match_ix, (offset, _)) in message
5982 .match_indices('`')
5983 .chain([(message.len(), "")])
5984 .enumerate()
5985 {
5986 message_without_backticks.push_str(&message[prev_offset..offset]);
5987 if inside_block {
5988 highlights.extend(prev_offset - match_ix..offset - match_ix);
5989 }
5990
5991 inside_block = !inside_block;
5992 prev_offset = offset + 1;
5993 }
5994
5995 (message_without_backticks, highlights)
5996}
5997
5998pub fn diagnostic_style(
5999 severity: DiagnosticSeverity,
6000 valid: bool,
6001 theme: &theme::Editor,
6002) -> DiagnosticStyle {
6003 match (severity, valid) {
6004 (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
6005 (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
6006 (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
6007 (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
6008 (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
6009 (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
6010 (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
6011 (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
6012 _ => theme.invalid_hint_diagnostic.clone(),
6013 }
6014}
6015
6016pub fn combine_syntax_and_fuzzy_match_highlights(
6017 text: &str,
6018 default_style: HighlightStyle,
6019 syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
6020 match_indices: &[usize],
6021) -> Vec<(Range<usize>, HighlightStyle)> {
6022 let mut result = Vec::new();
6023 let mut match_indices = match_indices.iter().copied().peekable();
6024
6025 for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
6026 {
6027 syntax_highlight.weight = None;
6028
6029 // Add highlights for any fuzzy match characters before the next
6030 // syntax highlight range.
6031 while let Some(&match_index) = match_indices.peek() {
6032 if match_index >= range.start {
6033 break;
6034 }
6035 match_indices.next();
6036 let end_index = char_ix_after(match_index, text);
6037 let mut match_style = default_style;
6038 match_style.weight = Some(fonts::Weight::BOLD);
6039 result.push((match_index..end_index, match_style));
6040 }
6041
6042 if range.start == usize::MAX {
6043 break;
6044 }
6045
6046 // Add highlights for any fuzzy match characters within the
6047 // syntax highlight range.
6048 let mut offset = range.start;
6049 while let Some(&match_index) = match_indices.peek() {
6050 if match_index >= range.end {
6051 break;
6052 }
6053
6054 match_indices.next();
6055 if match_index > offset {
6056 result.push((offset..match_index, syntax_highlight));
6057 }
6058
6059 let mut end_index = char_ix_after(match_index, text);
6060 while let Some(&next_match_index) = match_indices.peek() {
6061 if next_match_index == end_index && next_match_index < range.end {
6062 end_index = char_ix_after(next_match_index, text);
6063 match_indices.next();
6064 } else {
6065 break;
6066 }
6067 }
6068
6069 let mut match_style = syntax_highlight;
6070 match_style.weight = Some(fonts::Weight::BOLD);
6071 result.push((match_index..end_index, match_style));
6072 offset = end_index;
6073 }
6074
6075 if offset < range.end {
6076 result.push((offset..range.end, syntax_highlight));
6077 }
6078 }
6079
6080 fn char_ix_after(ix: usize, text: &str) -> usize {
6081 ix + text[ix..].chars().next().unwrap().len_utf8()
6082 }
6083
6084 result
6085}
6086
6087pub fn styled_runs_for_code_label<'a>(
6088 label: &'a CodeLabel,
6089 syntax_theme: &'a theme::SyntaxTheme,
6090) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
6091 let fade_out = HighlightStyle {
6092 fade_out: Some(0.35),
6093 ..Default::default()
6094 };
6095
6096 let mut prev_end = label.filter_range.end;
6097 label
6098 .runs
6099 .iter()
6100 .enumerate()
6101 .flat_map(move |(ix, (range, highlight_id))| {
6102 let style = if let Some(style) = highlight_id.style(syntax_theme) {
6103 style
6104 } else {
6105 return Default::default();
6106 };
6107 let mut muted_style = style.clone();
6108 muted_style.highlight(fade_out);
6109
6110 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
6111 if range.start >= label.filter_range.end {
6112 if range.start > prev_end {
6113 runs.push((prev_end..range.start, fade_out));
6114 }
6115 runs.push((range.clone(), muted_style));
6116 } else if range.end <= label.filter_range.end {
6117 runs.push((range.clone(), style));
6118 } else {
6119 runs.push((range.start..label.filter_range.end, style));
6120 runs.push((label.filter_range.end..range.end, muted_style));
6121 }
6122 prev_end = cmp::max(prev_end, range.end);
6123
6124 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
6125 runs.push((prev_end..label.text.len(), fade_out));
6126 }
6127
6128 runs
6129 })
6130}
6131
6132#[cfg(test)]
6133mod tests {
6134 use crate::test::marked_text_by;
6135
6136 use super::*;
6137 use gpui::{
6138 geometry::rect::RectF,
6139 platform::{WindowBounds, WindowOptions},
6140 };
6141 use language::{LanguageConfig, LanguageServerConfig};
6142 use lsp::FakeLanguageServer;
6143 use project::FakeFs;
6144 use smol::stream::StreamExt;
6145 use std::{cell::RefCell, rc::Rc, time::Instant};
6146 use text::Point;
6147 use unindent::Unindent;
6148 use util::test::sample_text;
6149 use workspace::FollowableItem;
6150
6151 #[gpui::test]
6152 fn test_edit_events(cx: &mut MutableAppContext) {
6153 populate_settings(cx);
6154 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6155
6156 let events = Rc::new(RefCell::new(Vec::new()));
6157 let (_, editor1) = cx.add_window(Default::default(), {
6158 let events = events.clone();
6159 |cx| {
6160 cx.subscribe(&cx.handle(), move |_, _, event, _| {
6161 if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6162 events.borrow_mut().push(("editor1", *event));
6163 }
6164 })
6165 .detach();
6166 Editor::for_buffer(buffer.clone(), None, cx)
6167 }
6168 });
6169 let (_, editor2) = cx.add_window(Default::default(), {
6170 let events = events.clone();
6171 |cx| {
6172 cx.subscribe(&cx.handle(), move |_, _, event, _| {
6173 if matches!(event, Event::Edited | Event::BufferEdited | Event::Dirtied) {
6174 events.borrow_mut().push(("editor2", *event));
6175 }
6176 })
6177 .detach();
6178 Editor::for_buffer(buffer.clone(), None, cx)
6179 }
6180 });
6181 assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6182
6183 // Mutating editor 1 will emit an `Edited` event only for that editor.
6184 editor1.update(cx, |editor, cx| editor.insert("X", cx));
6185 assert_eq!(
6186 mem::take(&mut *events.borrow_mut()),
6187 [
6188 ("editor1", Event::Edited),
6189 ("editor1", Event::BufferEdited),
6190 ("editor2", Event::BufferEdited),
6191 ("editor1", Event::Dirtied),
6192 ("editor2", Event::Dirtied)
6193 ]
6194 );
6195
6196 // Mutating editor 2 will emit an `Edited` event only for that editor.
6197 editor2.update(cx, |editor, cx| editor.delete(&Delete, cx));
6198 assert_eq!(
6199 mem::take(&mut *events.borrow_mut()),
6200 [
6201 ("editor2", Event::Edited),
6202 ("editor1", Event::BufferEdited),
6203 ("editor2", Event::BufferEdited),
6204 ]
6205 );
6206
6207 // Undoing on editor 1 will emit an `Edited` event only for that editor.
6208 editor1.update(cx, |editor, cx| editor.undo(&Undo, cx));
6209 assert_eq!(
6210 mem::take(&mut *events.borrow_mut()),
6211 [
6212 ("editor1", Event::Edited),
6213 ("editor1", Event::BufferEdited),
6214 ("editor2", Event::BufferEdited),
6215 ]
6216 );
6217
6218 // Redoing on editor 1 will emit an `Edited` event only for that editor.
6219 editor1.update(cx, |editor, cx| editor.redo(&Redo, cx));
6220 assert_eq!(
6221 mem::take(&mut *events.borrow_mut()),
6222 [
6223 ("editor1", Event::Edited),
6224 ("editor1", Event::BufferEdited),
6225 ("editor2", Event::BufferEdited),
6226 ]
6227 );
6228
6229 // Undoing on editor 2 will emit an `Edited` event only for that editor.
6230 editor2.update(cx, |editor, cx| editor.undo(&Undo, cx));
6231 assert_eq!(
6232 mem::take(&mut *events.borrow_mut()),
6233 [
6234 ("editor2", Event::Edited),
6235 ("editor1", Event::BufferEdited),
6236 ("editor2", Event::BufferEdited),
6237 ]
6238 );
6239
6240 // Redoing on editor 2 will emit an `Edited` event only for that editor.
6241 editor2.update(cx, |editor, cx| editor.redo(&Redo, cx));
6242 assert_eq!(
6243 mem::take(&mut *events.borrow_mut()),
6244 [
6245 ("editor2", Event::Edited),
6246 ("editor1", Event::BufferEdited),
6247 ("editor2", Event::BufferEdited),
6248 ]
6249 );
6250
6251 // No event is emitted when the mutation is a no-op.
6252 editor2.update(cx, |editor, cx| {
6253 editor.select_ranges([0..0], None, cx);
6254 editor.backspace(&Backspace, cx);
6255 });
6256 assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6257 }
6258
6259 #[gpui::test]
6260 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
6261 populate_settings(cx);
6262 let mut now = Instant::now();
6263 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
6264 let group_interval = buffer.read(cx).transaction_group_interval();
6265 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6266 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6267
6268 editor.update(cx, |editor, cx| {
6269 editor.start_transaction_at(now, cx);
6270 editor.select_ranges([2..4], None, cx);
6271 editor.insert("cd", cx);
6272 editor.end_transaction_at(now, cx);
6273 assert_eq!(editor.text(cx), "12cd56");
6274 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
6275
6276 editor.start_transaction_at(now, cx);
6277 editor.select_ranges([4..5], None, cx);
6278 editor.insert("e", cx);
6279 editor.end_transaction_at(now, cx);
6280 assert_eq!(editor.text(cx), "12cde6");
6281 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6282
6283 now += group_interval + Duration::from_millis(1);
6284 editor.select_ranges([2..2], None, cx);
6285
6286 // Simulate an edit in another editor
6287 buffer.update(cx, |buffer, cx| {
6288 buffer.start_transaction_at(now, cx);
6289 buffer.edit([0..1], "a", cx);
6290 buffer.edit([1..1], "b", cx);
6291 buffer.end_transaction_at(now, cx);
6292 });
6293
6294 assert_eq!(editor.text(cx), "ab2cde6");
6295 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
6296
6297 // Last transaction happened past the group interval in a different editor.
6298 // Undo it individually and don't restore selections.
6299 editor.undo(&Undo, cx);
6300 assert_eq!(editor.text(cx), "12cde6");
6301 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
6302
6303 // First two transactions happened within the group interval in this editor.
6304 // Undo them together and restore selections.
6305 editor.undo(&Undo, cx);
6306 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
6307 assert_eq!(editor.text(cx), "123456");
6308 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
6309
6310 // Redo the first two transactions together.
6311 editor.redo(&Redo, cx);
6312 assert_eq!(editor.text(cx), "12cde6");
6313 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
6314
6315 // Redo the last transaction on its own.
6316 editor.redo(&Redo, cx);
6317 assert_eq!(editor.text(cx), "ab2cde6");
6318 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
6319
6320 // Test empty transactions.
6321 editor.start_transaction_at(now, cx);
6322 editor.end_transaction_at(now, cx);
6323 editor.undo(&Undo, cx);
6324 assert_eq!(editor.text(cx), "12cde6");
6325 });
6326 }
6327
6328 #[gpui::test]
6329 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
6330 populate_settings(cx);
6331
6332 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
6333 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6334 editor.update(cx, |view, cx| {
6335 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6336 });
6337 assert_eq!(
6338 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6339 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6340 );
6341
6342 editor.update(cx, |view, cx| {
6343 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6344 });
6345
6346 assert_eq!(
6347 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6348 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6349 );
6350
6351 editor.update(cx, |view, cx| {
6352 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6353 });
6354
6355 assert_eq!(
6356 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6357 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6358 );
6359
6360 editor.update(cx, |view, cx| {
6361 view.end_selection(cx);
6362 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6363 });
6364
6365 assert_eq!(
6366 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6367 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6368 );
6369
6370 editor.update(cx, |view, cx| {
6371 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
6372 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
6373 });
6374
6375 assert_eq!(
6376 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6377 [
6378 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
6379 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
6380 ]
6381 );
6382
6383 editor.update(cx, |view, cx| {
6384 view.end_selection(cx);
6385 });
6386
6387 assert_eq!(
6388 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6389 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
6390 );
6391 }
6392
6393 #[gpui::test]
6394 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
6395 populate_settings(cx);
6396 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6397 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6398
6399 view.update(cx, |view, cx| {
6400 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6401 assert_eq!(
6402 view.selected_display_ranges(cx),
6403 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6404 );
6405 });
6406
6407 view.update(cx, |view, cx| {
6408 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6409 assert_eq!(
6410 view.selected_display_ranges(cx),
6411 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6412 );
6413 });
6414
6415 view.update(cx, |view, cx| {
6416 view.cancel(&Cancel, cx);
6417 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6418 assert_eq!(
6419 view.selected_display_ranges(cx),
6420 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6421 );
6422 });
6423 }
6424
6425 #[gpui::test]
6426 fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
6427 populate_settings(cx);
6428 use workspace::Item;
6429 let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6430 let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6431
6432 cx.add_window(Default::default(), |cx| {
6433 let mut editor = build_editor(buffer.clone(), cx);
6434 editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6435
6436 // Move the cursor a small distance.
6437 // Nothing is added to the navigation history.
6438 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6439 editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6440 assert!(nav_history.borrow_mut().pop_backward().is_none());
6441
6442 // Move the cursor a large distance.
6443 // The history can jump back to the previous position.
6444 editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6445 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6446 editor.navigate(nav_entry.data.unwrap(), cx);
6447 assert_eq!(nav_entry.item.id(), cx.view_id());
6448 assert_eq!(
6449 editor.selected_display_ranges(cx),
6450 &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6451 );
6452 assert!(nav_history.borrow_mut().pop_backward().is_none());
6453
6454 // Move the cursor a small distance via the mouse.
6455 // Nothing is added to the navigation history.
6456 editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6457 editor.end_selection(cx);
6458 assert_eq!(
6459 editor.selected_display_ranges(cx),
6460 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6461 );
6462 assert!(nav_history.borrow_mut().pop_backward().is_none());
6463
6464 // Move the cursor a large distance via the mouse.
6465 // The history can jump back to the previous position.
6466 editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6467 editor.end_selection(cx);
6468 assert_eq!(
6469 editor.selected_display_ranges(cx),
6470 &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6471 );
6472 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6473 editor.navigate(nav_entry.data.unwrap(), cx);
6474 assert_eq!(nav_entry.item.id(), cx.view_id());
6475 assert_eq!(
6476 editor.selected_display_ranges(cx),
6477 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6478 );
6479 assert!(nav_history.borrow_mut().pop_backward().is_none());
6480
6481 editor
6482 });
6483 }
6484
6485 #[gpui::test]
6486 fn test_cancel(cx: &mut gpui::MutableAppContext) {
6487 populate_settings(cx);
6488 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6489 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6490
6491 view.update(cx, |view, cx| {
6492 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6493 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6494 view.end_selection(cx);
6495
6496 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6497 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6498 view.end_selection(cx);
6499 assert_eq!(
6500 view.selected_display_ranges(cx),
6501 [
6502 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6503 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6504 ]
6505 );
6506 });
6507
6508 view.update(cx, |view, cx| {
6509 view.cancel(&Cancel, cx);
6510 assert_eq!(
6511 view.selected_display_ranges(cx),
6512 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
6513 );
6514 });
6515
6516 view.update(cx, |view, cx| {
6517 view.cancel(&Cancel, cx);
6518 assert_eq!(
6519 view.selected_display_ranges(cx),
6520 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6521 );
6522 });
6523 }
6524
6525 #[gpui::test]
6526 fn test_fold(cx: &mut gpui::MutableAppContext) {
6527 populate_settings(cx);
6528 let buffer = MultiBuffer::build_simple(
6529 &"
6530 impl Foo {
6531 // Hello!
6532
6533 fn a() {
6534 1
6535 }
6536
6537 fn b() {
6538 2
6539 }
6540
6541 fn c() {
6542 3
6543 }
6544 }
6545 "
6546 .unindent(),
6547 cx,
6548 );
6549 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6550
6551 view.update(cx, |view, cx| {
6552 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6553 view.fold(&Fold, cx);
6554 assert_eq!(
6555 view.display_text(cx),
6556 "
6557 impl Foo {
6558 // Hello!
6559
6560 fn a() {
6561 1
6562 }
6563
6564 fn b() {…
6565 }
6566
6567 fn c() {…
6568 }
6569 }
6570 "
6571 .unindent(),
6572 );
6573
6574 view.fold(&Fold, cx);
6575 assert_eq!(
6576 view.display_text(cx),
6577 "
6578 impl Foo {…
6579 }
6580 "
6581 .unindent(),
6582 );
6583
6584 view.unfold(&Unfold, cx);
6585 assert_eq!(
6586 view.display_text(cx),
6587 "
6588 impl Foo {
6589 // Hello!
6590
6591 fn a() {
6592 1
6593 }
6594
6595 fn b() {…
6596 }
6597
6598 fn c() {…
6599 }
6600 }
6601 "
6602 .unindent(),
6603 );
6604
6605 view.unfold(&Unfold, cx);
6606 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6607 });
6608 }
6609
6610 #[gpui::test]
6611 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6612 populate_settings(cx);
6613 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6614 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6615
6616 buffer.update(cx, |buffer, cx| {
6617 buffer.edit(
6618 vec![
6619 Point::new(1, 0)..Point::new(1, 0),
6620 Point::new(1, 1)..Point::new(1, 1),
6621 ],
6622 "\t",
6623 cx,
6624 );
6625 });
6626
6627 view.update(cx, |view, cx| {
6628 assert_eq!(
6629 view.selected_display_ranges(cx),
6630 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6631 );
6632
6633 view.move_down(&MoveDown, cx);
6634 assert_eq!(
6635 view.selected_display_ranges(cx),
6636 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6637 );
6638
6639 view.move_right(&MoveRight, cx);
6640 assert_eq!(
6641 view.selected_display_ranges(cx),
6642 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6643 );
6644
6645 view.move_left(&MoveLeft, cx);
6646 assert_eq!(
6647 view.selected_display_ranges(cx),
6648 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6649 );
6650
6651 view.move_up(&MoveUp, cx);
6652 assert_eq!(
6653 view.selected_display_ranges(cx),
6654 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6655 );
6656
6657 view.move_to_end(&MoveToEnd, cx);
6658 assert_eq!(
6659 view.selected_display_ranges(cx),
6660 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6661 );
6662
6663 view.move_to_beginning(&MoveToBeginning, cx);
6664 assert_eq!(
6665 view.selected_display_ranges(cx),
6666 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6667 );
6668
6669 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6670 view.select_to_beginning(&SelectToBeginning, cx);
6671 assert_eq!(
6672 view.selected_display_ranges(cx),
6673 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6674 );
6675
6676 view.select_to_end(&SelectToEnd, cx);
6677 assert_eq!(
6678 view.selected_display_ranges(cx),
6679 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6680 );
6681 });
6682 }
6683
6684 #[gpui::test]
6685 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6686 populate_settings(cx);
6687 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6688 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6689
6690 assert_eq!('ⓐ'.len_utf8(), 3);
6691 assert_eq!('α'.len_utf8(), 2);
6692
6693 view.update(cx, |view, cx| {
6694 view.fold_ranges(
6695 vec![
6696 Point::new(0, 6)..Point::new(0, 12),
6697 Point::new(1, 2)..Point::new(1, 4),
6698 Point::new(2, 4)..Point::new(2, 8),
6699 ],
6700 cx,
6701 );
6702 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
6703
6704 view.move_right(&MoveRight, cx);
6705 assert_eq!(
6706 view.selected_display_ranges(cx),
6707 &[empty_range(0, "ⓐ".len())]
6708 );
6709 view.move_right(&MoveRight, cx);
6710 assert_eq!(
6711 view.selected_display_ranges(cx),
6712 &[empty_range(0, "ⓐⓑ".len())]
6713 );
6714 view.move_right(&MoveRight, cx);
6715 assert_eq!(
6716 view.selected_display_ranges(cx),
6717 &[empty_range(0, "ⓐⓑ…".len())]
6718 );
6719
6720 view.move_down(&MoveDown, cx);
6721 assert_eq!(
6722 view.selected_display_ranges(cx),
6723 &[empty_range(1, "ab…".len())]
6724 );
6725 view.move_left(&MoveLeft, cx);
6726 assert_eq!(
6727 view.selected_display_ranges(cx),
6728 &[empty_range(1, "ab".len())]
6729 );
6730 view.move_left(&MoveLeft, cx);
6731 assert_eq!(
6732 view.selected_display_ranges(cx),
6733 &[empty_range(1, "a".len())]
6734 );
6735
6736 view.move_down(&MoveDown, cx);
6737 assert_eq!(
6738 view.selected_display_ranges(cx),
6739 &[empty_range(2, "α".len())]
6740 );
6741 view.move_right(&MoveRight, cx);
6742 assert_eq!(
6743 view.selected_display_ranges(cx),
6744 &[empty_range(2, "αβ".len())]
6745 );
6746 view.move_right(&MoveRight, cx);
6747 assert_eq!(
6748 view.selected_display_ranges(cx),
6749 &[empty_range(2, "αβ…".len())]
6750 );
6751 view.move_right(&MoveRight, cx);
6752 assert_eq!(
6753 view.selected_display_ranges(cx),
6754 &[empty_range(2, "αβ…ε".len())]
6755 );
6756
6757 view.move_up(&MoveUp, cx);
6758 assert_eq!(
6759 view.selected_display_ranges(cx),
6760 &[empty_range(1, "ab…e".len())]
6761 );
6762 view.move_up(&MoveUp, cx);
6763 assert_eq!(
6764 view.selected_display_ranges(cx),
6765 &[empty_range(0, "ⓐⓑ…ⓔ".len())]
6766 );
6767 view.move_left(&MoveLeft, cx);
6768 assert_eq!(
6769 view.selected_display_ranges(cx),
6770 &[empty_range(0, "ⓐⓑ…".len())]
6771 );
6772 view.move_left(&MoveLeft, cx);
6773 assert_eq!(
6774 view.selected_display_ranges(cx),
6775 &[empty_range(0, "ⓐⓑ".len())]
6776 );
6777 view.move_left(&MoveLeft, cx);
6778 assert_eq!(
6779 view.selected_display_ranges(cx),
6780 &[empty_range(0, "ⓐ".len())]
6781 );
6782 });
6783 }
6784
6785 #[gpui::test]
6786 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6787 populate_settings(cx);
6788 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6789 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
6790 view.update(cx, |view, cx| {
6791 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6792 view.move_down(&MoveDown, cx);
6793 assert_eq!(
6794 view.selected_display_ranges(cx),
6795 &[empty_range(1, "abcd".len())]
6796 );
6797
6798 view.move_down(&MoveDown, cx);
6799 assert_eq!(
6800 view.selected_display_ranges(cx),
6801 &[empty_range(2, "αβγ".len())]
6802 );
6803
6804 view.move_down(&MoveDown, cx);
6805 assert_eq!(
6806 view.selected_display_ranges(cx),
6807 &[empty_range(3, "abcd".len())]
6808 );
6809
6810 view.move_down(&MoveDown, cx);
6811 assert_eq!(
6812 view.selected_display_ranges(cx),
6813 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6814 );
6815
6816 view.move_up(&MoveUp, cx);
6817 assert_eq!(
6818 view.selected_display_ranges(cx),
6819 &[empty_range(3, "abcd".len())]
6820 );
6821
6822 view.move_up(&MoveUp, cx);
6823 assert_eq!(
6824 view.selected_display_ranges(cx),
6825 &[empty_range(2, "αβγ".len())]
6826 );
6827 });
6828 }
6829
6830 #[gpui::test]
6831 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6832 populate_settings(cx);
6833 let buffer = MultiBuffer::build_simple("abc\n def", cx);
6834 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6835 view.update(cx, |view, cx| {
6836 view.select_display_ranges(
6837 &[
6838 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6839 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6840 ],
6841 cx,
6842 );
6843 });
6844
6845 view.update(cx, |view, cx| {
6846 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6847 assert_eq!(
6848 view.selected_display_ranges(cx),
6849 &[
6850 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6851 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6852 ]
6853 );
6854 });
6855
6856 view.update(cx, |view, cx| {
6857 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6858 assert_eq!(
6859 view.selected_display_ranges(cx),
6860 &[
6861 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6862 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6863 ]
6864 );
6865 });
6866
6867 view.update(cx, |view, cx| {
6868 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6869 assert_eq!(
6870 view.selected_display_ranges(cx),
6871 &[
6872 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6873 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6874 ]
6875 );
6876 });
6877
6878 view.update(cx, |view, cx| {
6879 view.move_to_end_of_line(&MoveToEndOfLine, cx);
6880 assert_eq!(
6881 view.selected_display_ranges(cx),
6882 &[
6883 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6884 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6885 ]
6886 );
6887 });
6888
6889 // Moving to the end of line again is a no-op.
6890 view.update(cx, |view, cx| {
6891 view.move_to_end_of_line(&MoveToEndOfLine, cx);
6892 assert_eq!(
6893 view.selected_display_ranges(cx),
6894 &[
6895 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6896 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6897 ]
6898 );
6899 });
6900
6901 view.update(cx, |view, cx| {
6902 view.move_left(&MoveLeft, cx);
6903 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6904 assert_eq!(
6905 view.selected_display_ranges(cx),
6906 &[
6907 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6908 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6909 ]
6910 );
6911 });
6912
6913 view.update(cx, |view, cx| {
6914 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6915 assert_eq!(
6916 view.selected_display_ranges(cx),
6917 &[
6918 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6919 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
6920 ]
6921 );
6922 });
6923
6924 view.update(cx, |view, cx| {
6925 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6926 assert_eq!(
6927 view.selected_display_ranges(cx),
6928 &[
6929 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6930 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6931 ]
6932 );
6933 });
6934
6935 view.update(cx, |view, cx| {
6936 view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
6937 assert_eq!(
6938 view.selected_display_ranges(cx),
6939 &[
6940 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6941 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
6942 ]
6943 );
6944 });
6945
6946 view.update(cx, |view, cx| {
6947 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
6948 assert_eq!(view.display_text(cx), "ab\n de");
6949 assert_eq!(
6950 view.selected_display_ranges(cx),
6951 &[
6952 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6953 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6954 ]
6955 );
6956 });
6957
6958 view.update(cx, |view, cx| {
6959 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
6960 assert_eq!(view.display_text(cx), "\n");
6961 assert_eq!(
6962 view.selected_display_ranges(cx),
6963 &[
6964 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6965 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6966 ]
6967 );
6968 });
6969 }
6970
6971 #[gpui::test]
6972 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
6973 populate_settings(cx);
6974 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
6975 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
6976 view.update(cx, |view, cx| {
6977 view.select_display_ranges(
6978 &[
6979 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6980 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
6981 ],
6982 cx,
6983 );
6984
6985 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
6986 assert_selection_ranges(
6987 "use std::<>str::{foo, bar}\n\n {[]baz.qux()}",
6988 vec![('<', '>'), ('[', ']')],
6989 view,
6990 cx,
6991 );
6992
6993 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
6994 assert_selection_ranges(
6995 "use std<>::str::{foo, bar}\n\n []{baz.qux()}",
6996 vec![('<', '>'), ('[', ']')],
6997 view,
6998 cx,
6999 );
7000
7001 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7002 assert_selection_ranges(
7003 "use <>std::str::{foo, bar}\n\n[] {baz.qux()}",
7004 vec![('<', '>'), ('[', ']')],
7005 view,
7006 cx,
7007 );
7008
7009 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7010 assert_selection_ranges(
7011 "<>use std::str::{foo, bar}\n[]\n {baz.qux()}",
7012 vec![('<', '>'), ('[', ']')],
7013 view,
7014 cx,
7015 );
7016
7017 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7018 assert_selection_ranges(
7019 "<>use std::str::{foo, bar[]}\n\n {baz.qux()}",
7020 vec![('<', '>'), ('[', ']')],
7021 view,
7022 cx,
7023 );
7024
7025 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7026 assert_selection_ranges(
7027 "use<> std::str::{foo, bar}[]\n\n {baz.qux()}",
7028 vec![('<', '>'), ('[', ']')],
7029 view,
7030 cx,
7031 );
7032
7033 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7034 assert_selection_ranges(
7035 "use std<>::str::{foo, bar}\n[]\n {baz.qux()}",
7036 vec![('<', '>'), ('[', ']')],
7037 view,
7038 cx,
7039 );
7040
7041 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7042 assert_selection_ranges(
7043 "use std::<>str::{foo, bar}\n\n {[]baz.qux()}",
7044 vec![('<', '>'), ('[', ']')],
7045 view,
7046 cx,
7047 );
7048
7049 view.move_right(&MoveRight, cx);
7050 view.select_to_previous_word_start(&SelectToPreviousWordBoundary, cx);
7051 assert_selection_ranges(
7052 "use std::>s<tr::{foo, bar}\n\n {]b[az.qux()}",
7053 vec![('<', '>'), ('[', ']')],
7054 view,
7055 cx,
7056 );
7057
7058 view.select_to_previous_word_start(&SelectToPreviousWordBoundary, cx);
7059 assert_selection_ranges(
7060 "use std>::s<tr::{foo, bar}\n\n ]{b[az.qux()}",
7061 vec![('<', '>'), ('[', ']')],
7062 view,
7063 cx,
7064 );
7065
7066 view.select_to_next_word_end(&SelectToNextWordBoundary, cx);
7067 assert_selection_ranges(
7068 "use std::>s<tr::{foo, bar}\n\n {]b[az.qux()}",
7069 vec![('<', '>'), ('[', ']')],
7070 view,
7071 cx,
7072 );
7073 });
7074 }
7075
7076 #[gpui::test]
7077 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
7078 populate_settings(cx);
7079 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
7080 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7081
7082 view.update(cx, |view, cx| {
7083 view.set_wrap_width(Some(140.), cx);
7084 assert_eq!(
7085 view.display_text(cx),
7086 "use one::{\n two::three::\n four::five\n};"
7087 );
7088
7089 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
7090
7091 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7092 assert_eq!(
7093 view.selected_display_ranges(cx),
7094 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
7095 );
7096
7097 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7098 assert_eq!(
7099 view.selected_display_ranges(cx),
7100 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7101 );
7102
7103 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7104 assert_eq!(
7105 view.selected_display_ranges(cx),
7106 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7107 );
7108
7109 view.move_to_next_word_end(&MoveToNextWordEnd, cx);
7110 assert_eq!(
7111 view.selected_display_ranges(cx),
7112 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
7113 );
7114
7115 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7116 assert_eq!(
7117 view.selected_display_ranges(cx),
7118 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
7119 );
7120
7121 view.move_to_previous_word_start(&MoveToPreviousWordStart, cx);
7122 assert_eq!(
7123 view.selected_display_ranges(cx),
7124 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
7125 );
7126 });
7127 }
7128
7129 #[gpui::test]
7130 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
7131 populate_settings(cx);
7132 let buffer = MultiBuffer::build_simple("one two three four", cx);
7133 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7134
7135 view.update(cx, |view, cx| {
7136 view.select_display_ranges(
7137 &[
7138 // an empty selection - the preceding word fragment is deleted
7139 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7140 // characters selected - they are deleted
7141 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
7142 ],
7143 cx,
7144 );
7145 view.delete_to_previous_word_start(&DeleteToPreviousWordBoundary, cx);
7146 });
7147
7148 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
7149
7150 view.update(cx, |view, cx| {
7151 view.select_display_ranges(
7152 &[
7153 // an empty selection - the following word fragment is deleted
7154 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7155 // characters selected - they are deleted
7156 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
7157 ],
7158 cx,
7159 );
7160 view.delete_to_next_word_end(&DeleteToNextWordBoundary, cx);
7161 });
7162
7163 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
7164 }
7165
7166 #[gpui::test]
7167 fn test_newline(cx: &mut gpui::MutableAppContext) {
7168 populate_settings(cx);
7169 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
7170 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7171
7172 view.update(cx, |view, cx| {
7173 view.select_display_ranges(
7174 &[
7175 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7176 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7177 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
7178 ],
7179 cx,
7180 );
7181
7182 view.newline(&Newline, cx);
7183 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
7184 });
7185 }
7186
7187 #[gpui::test]
7188 fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
7189 populate_settings(cx);
7190 let buffer = MultiBuffer::build_simple(
7191 "
7192 a
7193 b(
7194 X
7195 )
7196 c(
7197 X
7198 )
7199 "
7200 .unindent()
7201 .as_str(),
7202 cx,
7203 );
7204
7205 let (_, editor) = cx.add_window(Default::default(), |cx| {
7206 let mut editor = build_editor(buffer.clone(), cx);
7207 editor.select_ranges(
7208 [
7209 Point::new(2, 4)..Point::new(2, 5),
7210 Point::new(5, 4)..Point::new(5, 5),
7211 ],
7212 None,
7213 cx,
7214 );
7215 editor
7216 });
7217
7218 // Edit the buffer directly, deleting ranges surrounding the editor's selections
7219 buffer.update(cx, |buffer, cx| {
7220 buffer.edit(
7221 [
7222 Point::new(1, 2)..Point::new(3, 0),
7223 Point::new(4, 2)..Point::new(6, 0),
7224 ],
7225 "",
7226 cx,
7227 );
7228 assert_eq!(
7229 buffer.read(cx).text(),
7230 "
7231 a
7232 b()
7233 c()
7234 "
7235 .unindent()
7236 );
7237 });
7238
7239 editor.update(cx, |editor, cx| {
7240 assert_eq!(
7241 editor.selected_ranges(cx),
7242 &[
7243 Point::new(1, 2)..Point::new(1, 2),
7244 Point::new(2, 2)..Point::new(2, 2),
7245 ],
7246 );
7247
7248 editor.newline(&Newline, cx);
7249 assert_eq!(
7250 editor.text(cx),
7251 "
7252 a
7253 b(
7254 )
7255 c(
7256 )
7257 "
7258 .unindent()
7259 );
7260
7261 // The selections are moved after the inserted newlines
7262 assert_eq!(
7263 editor.selected_ranges(cx),
7264 &[
7265 Point::new(2, 0)..Point::new(2, 0),
7266 Point::new(4, 0)..Point::new(4, 0),
7267 ],
7268 );
7269 });
7270 }
7271
7272 #[gpui::test]
7273 fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
7274 populate_settings(cx);
7275 let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
7276 let (_, editor) = cx.add_window(Default::default(), |cx| {
7277 let mut editor = build_editor(buffer.clone(), cx);
7278 editor.select_ranges([3..4, 11..12, 19..20], None, cx);
7279 editor
7280 });
7281
7282 // Edit the buffer directly, deleting ranges surrounding the editor's selections
7283 buffer.update(cx, |buffer, cx| {
7284 buffer.edit([2..5, 10..13, 18..21], "", cx);
7285 assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
7286 });
7287
7288 editor.update(cx, |editor, cx| {
7289 assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
7290
7291 editor.insert("Z", cx);
7292 assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
7293
7294 // The selections are moved after the inserted characters
7295 assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
7296 });
7297 }
7298
7299 #[gpui::test]
7300 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
7301 populate_settings(cx);
7302 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
7303 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7304
7305 view.update(cx, |view, cx| {
7306 // two selections on the same line
7307 view.select_display_ranges(
7308 &[
7309 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
7310 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
7311 ],
7312 cx,
7313 );
7314
7315 // indent from mid-tabstop to full tabstop
7316 view.tab(&Tab, cx);
7317 assert_eq!(view.text(cx), " one two\nthree\n four");
7318 assert_eq!(
7319 view.selected_display_ranges(cx),
7320 &[
7321 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7322 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
7323 ]
7324 );
7325
7326 // outdent from 1 tabstop to 0 tabstops
7327 view.outdent(&Outdent, cx);
7328 assert_eq!(view.text(cx), "one two\nthree\n four");
7329 assert_eq!(
7330 view.selected_display_ranges(cx),
7331 &[
7332 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
7333 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7334 ]
7335 );
7336
7337 // select across line ending
7338 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
7339
7340 // indent and outdent affect only the preceding line
7341 view.tab(&Tab, cx);
7342 assert_eq!(view.text(cx), "one two\n three\n four");
7343 assert_eq!(
7344 view.selected_display_ranges(cx),
7345 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
7346 );
7347 view.outdent(&Outdent, cx);
7348 assert_eq!(view.text(cx), "one two\nthree\n four");
7349 assert_eq!(
7350 view.selected_display_ranges(cx),
7351 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
7352 );
7353
7354 // Ensure that indenting/outdenting works when the cursor is at column 0.
7355 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7356 view.tab(&Tab, cx);
7357 assert_eq!(view.text(cx), "one two\n three\n four");
7358 assert_eq!(
7359 view.selected_display_ranges(cx),
7360 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
7361 );
7362
7363 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7364 view.outdent(&Outdent, cx);
7365 assert_eq!(view.text(cx), "one two\nthree\n four");
7366 assert_eq!(
7367 view.selected_display_ranges(cx),
7368 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
7369 );
7370 });
7371 }
7372
7373 #[gpui::test]
7374 fn test_backspace(cx: &mut gpui::MutableAppContext) {
7375 populate_settings(cx);
7376 let (_, view) = cx.add_window(Default::default(), |cx| {
7377 build_editor(MultiBuffer::build_simple("", cx), cx)
7378 });
7379
7380 view.update(cx, |view, cx| {
7381 view.set_text("one two three\nfour five six\nseven eight nine\nten\n", cx);
7382 view.select_display_ranges(
7383 &[
7384 // an empty selection - the preceding character is deleted
7385 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7386 // one character selected - it is deleted
7387 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7388 // a line suffix selected - it is deleted
7389 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7390 ],
7391 cx,
7392 );
7393 view.backspace(&Backspace, cx);
7394 assert_eq!(view.text(cx), "oe two three\nfou five six\nseven ten\n");
7395
7396 view.set_text(" one\n two\n three\n four", cx);
7397 view.select_display_ranges(
7398 &[
7399 // cursors at the the end of leading indent - last indent is deleted
7400 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
7401 DisplayPoint::new(1, 8)..DisplayPoint::new(1, 8),
7402 // cursors inside leading indent - overlapping indent deletions are coalesced
7403 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
7404 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7405 DisplayPoint::new(2, 6)..DisplayPoint::new(2, 6),
7406 // cursor at the beginning of a line - preceding newline is deleted
7407 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7408 // selection inside leading indent - only the selected character is deleted
7409 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3),
7410 ],
7411 cx,
7412 );
7413 view.backspace(&Backspace, cx);
7414 assert_eq!(view.text(cx), "one\n two\n three four");
7415 });
7416 }
7417
7418 #[gpui::test]
7419 fn test_delete(cx: &mut gpui::MutableAppContext) {
7420 populate_settings(cx);
7421 let buffer =
7422 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7423 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
7424
7425 view.update(cx, |view, cx| {
7426 view.select_display_ranges(
7427 &[
7428 // an empty selection - the following character is deleted
7429 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7430 // one character selected - it is deleted
7431 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7432 // a line suffix selected - it is deleted
7433 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7434 ],
7435 cx,
7436 );
7437 view.delete(&Delete, cx);
7438 });
7439
7440 assert_eq!(
7441 buffer.read(cx).read(cx).text(),
7442 "on two three\nfou five six\nseven ten\n"
7443 );
7444 }
7445
7446 #[gpui::test]
7447 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7448 populate_settings(cx);
7449 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7450 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7451 view.update(cx, |view, cx| {
7452 view.select_display_ranges(
7453 &[
7454 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7455 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7456 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7457 ],
7458 cx,
7459 );
7460 view.delete_line(&DeleteLine, cx);
7461 assert_eq!(view.display_text(cx), "ghi");
7462 assert_eq!(
7463 view.selected_display_ranges(cx),
7464 vec![
7465 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7466 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7467 ]
7468 );
7469 });
7470
7471 populate_settings(cx);
7472 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7473 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7474 view.update(cx, |view, cx| {
7475 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7476 view.delete_line(&DeleteLine, cx);
7477 assert_eq!(view.display_text(cx), "ghi\n");
7478 assert_eq!(
7479 view.selected_display_ranges(cx),
7480 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7481 );
7482 });
7483 }
7484
7485 #[gpui::test]
7486 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7487 populate_settings(cx);
7488 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7489 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7490 view.update(cx, |view, cx| {
7491 view.select_display_ranges(
7492 &[
7493 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7494 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7495 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7496 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7497 ],
7498 cx,
7499 );
7500 view.duplicate_line(&DuplicateLine, cx);
7501 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7502 assert_eq!(
7503 view.selected_display_ranges(cx),
7504 vec![
7505 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7506 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7507 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7508 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7509 ]
7510 );
7511 });
7512
7513 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7514 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7515 view.update(cx, |view, cx| {
7516 view.select_display_ranges(
7517 &[
7518 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7519 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7520 ],
7521 cx,
7522 );
7523 view.duplicate_line(&DuplicateLine, cx);
7524 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7525 assert_eq!(
7526 view.selected_display_ranges(cx),
7527 vec![
7528 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7529 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7530 ]
7531 );
7532 });
7533 }
7534
7535 #[gpui::test]
7536 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7537 populate_settings(cx);
7538 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7539 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7540 view.update(cx, |view, cx| {
7541 view.fold_ranges(
7542 vec![
7543 Point::new(0, 2)..Point::new(1, 2),
7544 Point::new(2, 3)..Point::new(4, 1),
7545 Point::new(7, 0)..Point::new(8, 4),
7546 ],
7547 cx,
7548 );
7549 view.select_display_ranges(
7550 &[
7551 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7552 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7553 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7554 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7555 ],
7556 cx,
7557 );
7558 assert_eq!(
7559 view.display_text(cx),
7560 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7561 );
7562
7563 view.move_line_up(&MoveLineUp, cx);
7564 assert_eq!(
7565 view.display_text(cx),
7566 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7567 );
7568 assert_eq!(
7569 view.selected_display_ranges(cx),
7570 vec![
7571 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7572 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7573 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7574 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7575 ]
7576 );
7577 });
7578
7579 view.update(cx, |view, cx| {
7580 view.move_line_down(&MoveLineDown, cx);
7581 assert_eq!(
7582 view.display_text(cx),
7583 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7584 );
7585 assert_eq!(
7586 view.selected_display_ranges(cx),
7587 vec![
7588 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7589 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7590 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7591 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7592 ]
7593 );
7594 });
7595
7596 view.update(cx, |view, cx| {
7597 view.move_line_down(&MoveLineDown, cx);
7598 assert_eq!(
7599 view.display_text(cx),
7600 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7601 );
7602 assert_eq!(
7603 view.selected_display_ranges(cx),
7604 vec![
7605 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7606 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7607 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7608 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7609 ]
7610 );
7611 });
7612
7613 view.update(cx, |view, cx| {
7614 view.move_line_up(&MoveLineUp, cx);
7615 assert_eq!(
7616 view.display_text(cx),
7617 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7618 );
7619 assert_eq!(
7620 view.selected_display_ranges(cx),
7621 vec![
7622 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7623 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7624 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7625 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7626 ]
7627 );
7628 });
7629 }
7630
7631 #[gpui::test]
7632 fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7633 populate_settings(cx);
7634 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7635 let snapshot = buffer.read(cx).snapshot(cx);
7636 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7637 editor.update(cx, |editor, cx| {
7638 editor.insert_blocks(
7639 [BlockProperties {
7640 position: snapshot.anchor_after(Point::new(2, 0)),
7641 disposition: BlockDisposition::Below,
7642 height: 1,
7643 render: Arc::new(|_| Empty::new().boxed()),
7644 }],
7645 cx,
7646 );
7647 editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7648 editor.move_line_down(&MoveLineDown, cx);
7649 });
7650 }
7651
7652 #[gpui::test]
7653 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7654 populate_settings(cx);
7655 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7656 let view = cx
7657 .add_window(Default::default(), |cx| build_editor(buffer.clone(), cx))
7658 .1;
7659
7660 // Cut with three selections. Clipboard text is divided into three slices.
7661 view.update(cx, |view, cx| {
7662 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7663 view.cut(&Cut, cx);
7664 assert_eq!(view.display_text(cx), "two four six ");
7665 });
7666
7667 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7668 view.update(cx, |view, cx| {
7669 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7670 view.paste(&Paste, cx);
7671 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7672 assert_eq!(
7673 view.selected_display_ranges(cx),
7674 &[
7675 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7676 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7677 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7678 ]
7679 );
7680 });
7681
7682 // Paste again but with only two cursors. Since the number of cursors doesn't
7683 // match the number of slices in the clipboard, the entire clipboard text
7684 // is pasted at each cursor.
7685 view.update(cx, |view, cx| {
7686 view.select_ranges(vec![0..0, 31..31], None, cx);
7687 view.handle_input(&Input("( ".into()), cx);
7688 view.paste(&Paste, cx);
7689 view.handle_input(&Input(") ".into()), cx);
7690 assert_eq!(
7691 view.display_text(cx),
7692 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7693 );
7694 });
7695
7696 view.update(cx, |view, cx| {
7697 view.select_ranges(vec![0..0], None, cx);
7698 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7699 assert_eq!(
7700 view.display_text(cx),
7701 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7702 );
7703 });
7704
7705 // Cut with three selections, one of which is full-line.
7706 view.update(cx, |view, cx| {
7707 view.select_display_ranges(
7708 &[
7709 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7710 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7711 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7712 ],
7713 cx,
7714 );
7715 view.cut(&Cut, cx);
7716 assert_eq!(
7717 view.display_text(cx),
7718 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7719 );
7720 });
7721
7722 // Paste with three selections, noticing how the copied selection that was full-line
7723 // gets inserted before the second cursor.
7724 view.update(cx, |view, cx| {
7725 view.select_display_ranges(
7726 &[
7727 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7728 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7729 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7730 ],
7731 cx,
7732 );
7733 view.paste(&Paste, cx);
7734 assert_eq!(
7735 view.display_text(cx),
7736 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7737 );
7738 assert_eq!(
7739 view.selected_display_ranges(cx),
7740 &[
7741 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7742 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7743 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7744 ]
7745 );
7746 });
7747
7748 // Copy with a single cursor only, which writes the whole line into the clipboard.
7749 view.update(cx, |view, cx| {
7750 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7751 view.copy(&Copy, cx);
7752 });
7753
7754 // Paste with three selections, noticing how the copied full-line selection is inserted
7755 // before the empty selections but replaces the selection that is non-empty.
7756 view.update(cx, |view, cx| {
7757 view.select_display_ranges(
7758 &[
7759 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7760 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7761 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7762 ],
7763 cx,
7764 );
7765 view.paste(&Paste, cx);
7766 assert_eq!(
7767 view.display_text(cx),
7768 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7769 );
7770 assert_eq!(
7771 view.selected_display_ranges(cx),
7772 &[
7773 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7774 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7775 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7776 ]
7777 );
7778 });
7779 }
7780
7781 #[gpui::test]
7782 fn test_select_all(cx: &mut gpui::MutableAppContext) {
7783 populate_settings(cx);
7784 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7785 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7786 view.update(cx, |view, cx| {
7787 view.select_all(&SelectAll, cx);
7788 assert_eq!(
7789 view.selected_display_ranges(cx),
7790 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7791 );
7792 });
7793 }
7794
7795 #[gpui::test]
7796 fn test_select_line(cx: &mut gpui::MutableAppContext) {
7797 populate_settings(cx);
7798 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7799 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7800 view.update(cx, |view, cx| {
7801 view.select_display_ranges(
7802 &[
7803 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7804 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7805 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7806 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7807 ],
7808 cx,
7809 );
7810 view.select_line(&SelectLine, cx);
7811 assert_eq!(
7812 view.selected_display_ranges(cx),
7813 vec![
7814 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7815 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7816 ]
7817 );
7818 });
7819
7820 view.update(cx, |view, cx| {
7821 view.select_line(&SelectLine, cx);
7822 assert_eq!(
7823 view.selected_display_ranges(cx),
7824 vec![
7825 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7826 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7827 ]
7828 );
7829 });
7830
7831 view.update(cx, |view, cx| {
7832 view.select_line(&SelectLine, cx);
7833 assert_eq!(
7834 view.selected_display_ranges(cx),
7835 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7836 );
7837 });
7838 }
7839
7840 #[gpui::test]
7841 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7842 populate_settings(cx);
7843 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7844 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7845 view.update(cx, |view, cx| {
7846 view.fold_ranges(
7847 vec![
7848 Point::new(0, 2)..Point::new(1, 2),
7849 Point::new(2, 3)..Point::new(4, 1),
7850 Point::new(7, 0)..Point::new(8, 4),
7851 ],
7852 cx,
7853 );
7854 view.select_display_ranges(
7855 &[
7856 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7857 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7858 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7859 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7860 ],
7861 cx,
7862 );
7863 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
7864 });
7865
7866 view.update(cx, |view, cx| {
7867 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7868 assert_eq!(
7869 view.display_text(cx),
7870 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
7871 );
7872 assert_eq!(
7873 view.selected_display_ranges(cx),
7874 [
7875 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7876 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7877 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7878 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
7879 ]
7880 );
7881 });
7882
7883 view.update(cx, |view, cx| {
7884 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
7885 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7886 assert_eq!(
7887 view.display_text(cx),
7888 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
7889 );
7890 assert_eq!(
7891 view.selected_display_ranges(cx),
7892 [
7893 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
7894 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7895 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7896 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
7897 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
7898 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
7899 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
7900 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
7901 ]
7902 );
7903 });
7904 }
7905
7906 #[gpui::test]
7907 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
7908 populate_settings(cx);
7909 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
7910 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, cx));
7911
7912 view.update(cx, |view, cx| {
7913 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
7914 });
7915 view.update(cx, |view, cx| {
7916 view.add_selection_above(&AddSelectionAbove, cx);
7917 assert_eq!(
7918 view.selected_display_ranges(cx),
7919 vec![
7920 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7921 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7922 ]
7923 );
7924 });
7925
7926 view.update(cx, |view, cx| {
7927 view.add_selection_above(&AddSelectionAbove, cx);
7928 assert_eq!(
7929 view.selected_display_ranges(cx),
7930 vec![
7931 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7932 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7933 ]
7934 );
7935 });
7936
7937 view.update(cx, |view, cx| {
7938 view.add_selection_below(&AddSelectionBelow, cx);
7939 assert_eq!(
7940 view.selected_display_ranges(cx),
7941 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7942 );
7943 });
7944
7945 view.update(cx, |view, cx| {
7946 view.add_selection_below(&AddSelectionBelow, cx);
7947 assert_eq!(
7948 view.selected_display_ranges(cx),
7949 vec![
7950 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7951 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7952 ]
7953 );
7954 });
7955
7956 view.update(cx, |view, cx| {
7957 view.add_selection_below(&AddSelectionBelow, cx);
7958 assert_eq!(
7959 view.selected_display_ranges(cx),
7960 vec![
7961 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7962 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7963 ]
7964 );
7965 });
7966
7967 view.update(cx, |view, cx| {
7968 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
7969 });
7970 view.update(cx, |view, cx| {
7971 view.add_selection_below(&AddSelectionBelow, cx);
7972 assert_eq!(
7973 view.selected_display_ranges(cx),
7974 vec![
7975 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7976 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7977 ]
7978 );
7979 });
7980
7981 view.update(cx, |view, cx| {
7982 view.add_selection_below(&AddSelectionBelow, cx);
7983 assert_eq!(
7984 view.selected_display_ranges(cx),
7985 vec![
7986 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7987 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7988 ]
7989 );
7990 });
7991
7992 view.update(cx, |view, cx| {
7993 view.add_selection_above(&AddSelectionAbove, cx);
7994 assert_eq!(
7995 view.selected_display_ranges(cx),
7996 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7997 );
7998 });
7999
8000 view.update(cx, |view, cx| {
8001 view.add_selection_above(&AddSelectionAbove, cx);
8002 assert_eq!(
8003 view.selected_display_ranges(cx),
8004 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
8005 );
8006 });
8007
8008 view.update(cx, |view, cx| {
8009 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
8010 view.add_selection_below(&AddSelectionBelow, cx);
8011 assert_eq!(
8012 view.selected_display_ranges(cx),
8013 vec![
8014 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8015 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8016 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8017 ]
8018 );
8019 });
8020
8021 view.update(cx, |view, cx| {
8022 view.add_selection_below(&AddSelectionBelow, cx);
8023 assert_eq!(
8024 view.selected_display_ranges(cx),
8025 vec![
8026 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8027 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8028 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8029 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
8030 ]
8031 );
8032 });
8033
8034 view.update(cx, |view, cx| {
8035 view.add_selection_above(&AddSelectionAbove, cx);
8036 assert_eq!(
8037 view.selected_display_ranges(cx),
8038 vec![
8039 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
8040 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
8041 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
8042 ]
8043 );
8044 });
8045
8046 view.update(cx, |view, cx| {
8047 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
8048 });
8049 view.update(cx, |view, cx| {
8050 view.add_selection_above(&AddSelectionAbove, cx);
8051 assert_eq!(
8052 view.selected_display_ranges(cx),
8053 vec![
8054 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
8055 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8056 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8057 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8058 ]
8059 );
8060 });
8061
8062 view.update(cx, |view, cx| {
8063 view.add_selection_below(&AddSelectionBelow, cx);
8064 assert_eq!(
8065 view.selected_display_ranges(cx),
8066 vec![
8067 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
8068 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
8069 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
8070 ]
8071 );
8072 });
8073 }
8074
8075 #[gpui::test]
8076 async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
8077 cx.update(populate_settings);
8078 let language = Arc::new(Language::new(
8079 LanguageConfig::default(),
8080 Some(tree_sitter_rust::language()),
8081 ));
8082
8083 let text = r#"
8084 use mod1::mod2::{mod3, mod4};
8085
8086 fn fn_1(param1: bool, param2: &str) {
8087 let var1 = "text";
8088 }
8089 "#
8090 .unindent();
8091
8092 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8093 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8094 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8095 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8096 .await;
8097
8098 view.update(cx, |view, cx| {
8099 view.select_display_ranges(
8100 &[
8101 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8102 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8103 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8104 ],
8105 cx,
8106 );
8107 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8108 });
8109 assert_eq!(
8110 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8111 &[
8112 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8113 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8114 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8115 ]
8116 );
8117
8118 view.update(cx, |view, cx| {
8119 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8120 });
8121 assert_eq!(
8122 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8123 &[
8124 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8125 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8126 ]
8127 );
8128
8129 view.update(cx, |view, cx| {
8130 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8131 });
8132 assert_eq!(
8133 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8134 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8135 );
8136
8137 // Trying to expand the selected syntax node one more time has no effect.
8138 view.update(cx, |view, cx| {
8139 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8140 });
8141 assert_eq!(
8142 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8143 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
8144 );
8145
8146 view.update(cx, |view, cx| {
8147 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8148 });
8149 assert_eq!(
8150 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8151 &[
8152 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8153 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
8154 ]
8155 );
8156
8157 view.update(cx, |view, cx| {
8158 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8159 });
8160 assert_eq!(
8161 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8162 &[
8163 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
8164 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8165 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
8166 ]
8167 );
8168
8169 view.update(cx, |view, cx| {
8170 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8171 });
8172 assert_eq!(
8173 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8174 &[
8175 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8176 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8177 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8178 ]
8179 );
8180
8181 // Trying to shrink the selected syntax node one more time has no effect.
8182 view.update(cx, |view, cx| {
8183 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
8184 });
8185 assert_eq!(
8186 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8187 &[
8188 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
8189 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
8190 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
8191 ]
8192 );
8193
8194 // Ensure that we keep expanding the selection if the larger selection starts or ends within
8195 // a fold.
8196 view.update(cx, |view, cx| {
8197 view.fold_ranges(
8198 vec![
8199 Point::new(0, 21)..Point::new(0, 24),
8200 Point::new(3, 20)..Point::new(3, 22),
8201 ],
8202 cx,
8203 );
8204 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
8205 });
8206 assert_eq!(
8207 view.update(cx, |view, cx| view.selected_display_ranges(cx)),
8208 &[
8209 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
8210 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
8211 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
8212 ]
8213 );
8214 }
8215
8216 #[gpui::test]
8217 async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
8218 cx.update(populate_settings);
8219 let language = Arc::new(
8220 Language::new(
8221 LanguageConfig {
8222 brackets: vec![
8223 BracketPair {
8224 start: "{".to_string(),
8225 end: "}".to_string(),
8226 close: false,
8227 newline: true,
8228 },
8229 BracketPair {
8230 start: "(".to_string(),
8231 end: ")".to_string(),
8232 close: false,
8233 newline: true,
8234 },
8235 ],
8236 ..Default::default()
8237 },
8238 Some(tree_sitter_rust::language()),
8239 )
8240 .with_indents_query(
8241 r#"
8242 (_ "(" ")" @end) @indent
8243 (_ "{" "}" @end) @indent
8244 "#,
8245 )
8246 .unwrap(),
8247 );
8248
8249 let text = "fn a() {}";
8250
8251 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8252 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8253 let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8254 editor
8255 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
8256 .await;
8257
8258 editor.update(cx, |editor, cx| {
8259 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
8260 editor.newline(&Newline, cx);
8261 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
8262 assert_eq!(
8263 editor.selected_ranges(cx),
8264 &[
8265 Point::new(1, 4)..Point::new(1, 4),
8266 Point::new(3, 4)..Point::new(3, 4),
8267 Point::new(5, 0)..Point::new(5, 0)
8268 ]
8269 );
8270 });
8271 }
8272
8273 #[gpui::test]
8274 async fn test_autoclose_pairs(cx: &mut gpui::TestAppContext) {
8275 cx.update(populate_settings);
8276 let language = Arc::new(Language::new(
8277 LanguageConfig {
8278 brackets: vec![
8279 BracketPair {
8280 start: "{".to_string(),
8281 end: "}".to_string(),
8282 close: true,
8283 newline: true,
8284 },
8285 BracketPair {
8286 start: "/*".to_string(),
8287 end: " */".to_string(),
8288 close: true,
8289 newline: true,
8290 },
8291 ],
8292 autoclose_before: "})]".to_string(),
8293 ..Default::default()
8294 },
8295 Some(tree_sitter_rust::language()),
8296 ));
8297
8298 let text = r#"
8299 a
8300
8301 /
8302
8303 "#
8304 .unindent();
8305
8306 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8307 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8308 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8309 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8310 .await;
8311
8312 view.update(cx, |view, cx| {
8313 view.select_display_ranges(
8314 &[
8315 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8316 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8317 ],
8318 cx,
8319 );
8320
8321 view.handle_input(&Input("{".to_string()), cx);
8322 view.handle_input(&Input("{".to_string()), cx);
8323 view.handle_input(&Input("{".to_string()), cx);
8324 assert_eq!(
8325 view.text(cx),
8326 "
8327 {{{}}}
8328 {{{}}}
8329 /
8330
8331 "
8332 .unindent()
8333 );
8334
8335 view.move_right(&MoveRight, cx);
8336 view.handle_input(&Input("}".to_string()), cx);
8337 view.handle_input(&Input("}".to_string()), cx);
8338 view.handle_input(&Input("}".to_string()), cx);
8339 assert_eq!(
8340 view.text(cx),
8341 "
8342 {{{}}}}
8343 {{{}}}}
8344 /
8345
8346 "
8347 .unindent()
8348 );
8349
8350 view.undo(&Undo, cx);
8351 view.handle_input(&Input("/".to_string()), cx);
8352 view.handle_input(&Input("*".to_string()), cx);
8353 assert_eq!(
8354 view.text(cx),
8355 "
8356 /* */
8357 /* */
8358 /
8359
8360 "
8361 .unindent()
8362 );
8363
8364 view.undo(&Undo, cx);
8365 view.select_display_ranges(
8366 &[
8367 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8368 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8369 ],
8370 cx,
8371 );
8372 view.handle_input(&Input("*".to_string()), cx);
8373 assert_eq!(
8374 view.text(cx),
8375 "
8376 a
8377
8378 /*
8379 *
8380 "
8381 .unindent()
8382 );
8383
8384 // Don't autoclose if the next character isn't whitespace and isn't
8385 // listed in the language's "autoclose_before" section.
8386 view.finalize_last_transaction(cx);
8387 view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
8388 view.handle_input(&Input("{".to_string()), cx);
8389 assert_eq!(
8390 view.text(cx),
8391 "
8392 {a
8393
8394 /*
8395 *
8396 "
8397 .unindent()
8398 );
8399
8400 view.undo(&Undo, cx);
8401 view.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1)], cx);
8402 view.handle_input(&Input("{".to_string()), cx);
8403 assert_eq!(
8404 view.text(cx),
8405 "
8406 {a}
8407
8408 /*
8409 *
8410 "
8411 .unindent()
8412 );
8413 assert_eq!(
8414 view.selected_display_ranges(cx),
8415 [DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)]
8416 );
8417 });
8418 }
8419
8420 #[gpui::test]
8421 async fn test_snippets(cx: &mut gpui::TestAppContext) {
8422 cx.update(populate_settings);
8423
8424 let text = "
8425 a. b
8426 a. b
8427 a. b
8428 "
8429 .unindent();
8430 let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8431 let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8432
8433 editor.update(cx, |editor, cx| {
8434 let buffer = &editor.snapshot(cx).buffer_snapshot;
8435 let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8436 let insertion_ranges = [
8437 Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8438 Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8439 Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8440 ];
8441
8442 editor
8443 .insert_snippet(&insertion_ranges, snippet, cx)
8444 .unwrap();
8445 assert_eq!(
8446 editor.text(cx),
8447 "
8448 a.f(one, two, three) b
8449 a.f(one, two, three) b
8450 a.f(one, two, three) b
8451 "
8452 .unindent()
8453 );
8454 assert_eq!(
8455 editor.selected_ranges::<Point>(cx),
8456 &[
8457 Point::new(0, 4)..Point::new(0, 7),
8458 Point::new(0, 14)..Point::new(0, 19),
8459 Point::new(1, 4)..Point::new(1, 7),
8460 Point::new(1, 14)..Point::new(1, 19),
8461 Point::new(2, 4)..Point::new(2, 7),
8462 Point::new(2, 14)..Point::new(2, 19),
8463 ]
8464 );
8465
8466 // Can't move earlier than the first tab stop
8467 editor.move_to_prev_snippet_tabstop(cx);
8468 assert_eq!(
8469 editor.selected_ranges::<Point>(cx),
8470 &[
8471 Point::new(0, 4)..Point::new(0, 7),
8472 Point::new(0, 14)..Point::new(0, 19),
8473 Point::new(1, 4)..Point::new(1, 7),
8474 Point::new(1, 14)..Point::new(1, 19),
8475 Point::new(2, 4)..Point::new(2, 7),
8476 Point::new(2, 14)..Point::new(2, 19),
8477 ]
8478 );
8479
8480 assert!(editor.move_to_next_snippet_tabstop(cx));
8481 assert_eq!(
8482 editor.selected_ranges::<Point>(cx),
8483 &[
8484 Point::new(0, 9)..Point::new(0, 12),
8485 Point::new(1, 9)..Point::new(1, 12),
8486 Point::new(2, 9)..Point::new(2, 12)
8487 ]
8488 );
8489
8490 editor.move_to_prev_snippet_tabstop(cx);
8491 assert_eq!(
8492 editor.selected_ranges::<Point>(cx),
8493 &[
8494 Point::new(0, 4)..Point::new(0, 7),
8495 Point::new(0, 14)..Point::new(0, 19),
8496 Point::new(1, 4)..Point::new(1, 7),
8497 Point::new(1, 14)..Point::new(1, 19),
8498 Point::new(2, 4)..Point::new(2, 7),
8499 Point::new(2, 14)..Point::new(2, 19),
8500 ]
8501 );
8502
8503 assert!(editor.move_to_next_snippet_tabstop(cx));
8504 assert!(editor.move_to_next_snippet_tabstop(cx));
8505 assert_eq!(
8506 editor.selected_ranges::<Point>(cx),
8507 &[
8508 Point::new(0, 20)..Point::new(0, 20),
8509 Point::new(1, 20)..Point::new(1, 20),
8510 Point::new(2, 20)..Point::new(2, 20)
8511 ]
8512 );
8513
8514 // As soon as the last tab stop is reached, snippet state is gone
8515 editor.move_to_prev_snippet_tabstop(cx);
8516 assert_eq!(
8517 editor.selected_ranges::<Point>(cx),
8518 &[
8519 Point::new(0, 20)..Point::new(0, 20),
8520 Point::new(1, 20)..Point::new(1, 20),
8521 Point::new(2, 20)..Point::new(2, 20)
8522 ]
8523 );
8524 });
8525 }
8526
8527 #[gpui::test]
8528 async fn test_completion(cx: &mut gpui::TestAppContext) {
8529 cx.update(populate_settings);
8530
8531 let (mut language_server_config, mut fake_servers) = LanguageServerConfig::fake();
8532 language_server_config.set_fake_capabilities(lsp::ServerCapabilities {
8533 completion_provider: Some(lsp::CompletionOptions {
8534 trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
8535 ..Default::default()
8536 }),
8537 ..Default::default()
8538 });
8539 let language = Arc::new(Language::new(
8540 LanguageConfig {
8541 name: "Rust".into(),
8542 path_suffixes: vec!["rs".to_string()],
8543 language_server: Some(language_server_config),
8544 ..Default::default()
8545 },
8546 Some(tree_sitter_rust::language()),
8547 ));
8548
8549 let text = "
8550 one
8551 two
8552 three
8553 "
8554 .unindent();
8555
8556 let fs = FakeFs::new(cx.background().clone());
8557 fs.insert_file("/file.rs", text).await;
8558
8559 let project = Project::test(fs, cx);
8560 project.update(cx, |project, _| project.languages().add(language));
8561
8562 let worktree_id = project
8563 .update(cx, |project, cx| {
8564 project.find_or_create_local_worktree("/file.rs", true, cx)
8565 })
8566 .await
8567 .unwrap()
8568 .0
8569 .read_with(cx, |tree, _| tree.id());
8570 let buffer = project
8571 .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
8572 .await
8573 .unwrap();
8574 let mut fake_server = fake_servers.next().await.unwrap();
8575
8576 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8577 let (_, editor) = cx.add_window(|cx| build_editor(buffer, cx));
8578
8579 editor.update(cx, |editor, cx| {
8580 editor.project = Some(project);
8581 editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
8582 editor.handle_input(&Input(".".to_string()), cx);
8583 });
8584
8585 handle_completion_request(
8586 &mut fake_server,
8587 "/file.rs",
8588 Point::new(0, 4),
8589 vec![
8590 (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
8591 (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
8592 ],
8593 )
8594 .await;
8595 editor
8596 .condition(&cx, |editor, _| editor.context_menu_visible())
8597 .await;
8598
8599 let apply_additional_edits = editor.update(cx, |editor, cx| {
8600 editor.move_down(&MoveDown, cx);
8601 let apply_additional_edits = editor
8602 .confirm_completion(&ConfirmCompletion(None), cx)
8603 .unwrap();
8604 assert_eq!(
8605 editor.text(cx),
8606 "
8607 one.second_completion
8608 two
8609 three
8610 "
8611 .unindent()
8612 );
8613 apply_additional_edits
8614 });
8615
8616 handle_resolve_completion_request(
8617 &mut fake_server,
8618 Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
8619 )
8620 .await;
8621 apply_additional_edits.await.unwrap();
8622 assert_eq!(
8623 editor.read_with(cx, |editor, cx| editor.text(cx)),
8624 "
8625 one.second_completion
8626 two
8627 three
8628 additional edit
8629 "
8630 .unindent()
8631 );
8632
8633 editor.update(cx, |editor, cx| {
8634 editor.select_ranges(
8635 [
8636 Point::new(1, 3)..Point::new(1, 3),
8637 Point::new(2, 5)..Point::new(2, 5),
8638 ],
8639 None,
8640 cx,
8641 );
8642
8643 editor.handle_input(&Input(" ".to_string()), cx);
8644 assert!(editor.context_menu.is_none());
8645 editor.handle_input(&Input("s".to_string()), cx);
8646 assert!(editor.context_menu.is_none());
8647 });
8648
8649 handle_completion_request(
8650 &mut fake_server,
8651 "/file.rs",
8652 Point::new(2, 7),
8653 vec![
8654 (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8655 (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8656 (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8657 ],
8658 )
8659 .await;
8660 editor
8661 .condition(&cx, |editor, _| editor.context_menu_visible())
8662 .await;
8663
8664 editor.update(cx, |editor, cx| {
8665 editor.handle_input(&Input("i".to_string()), cx);
8666 });
8667
8668 handle_completion_request(
8669 &mut fake_server,
8670 "/file.rs",
8671 Point::new(2, 8),
8672 vec![
8673 (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8674 (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8675 (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8676 ],
8677 )
8678 .await;
8679 editor
8680 .condition(&cx, |editor, _| editor.context_menu_visible())
8681 .await;
8682
8683 let apply_additional_edits = editor.update(cx, |editor, cx| {
8684 let apply_additional_edits = editor
8685 .confirm_completion(&ConfirmCompletion(None), cx)
8686 .unwrap();
8687 assert_eq!(
8688 editor.text(cx),
8689 "
8690 one.second_completion
8691 two sixth_completion
8692 three sixth_completion
8693 additional edit
8694 "
8695 .unindent()
8696 );
8697 apply_additional_edits
8698 });
8699 handle_resolve_completion_request(&mut fake_server, None).await;
8700 apply_additional_edits.await.unwrap();
8701
8702 async fn handle_completion_request(
8703 fake: &mut FakeLanguageServer,
8704 path: &'static str,
8705 position: Point,
8706 completions: Vec<(Range<Point>, &'static str)>,
8707 ) {
8708 fake.handle_request::<lsp::request::Completion, _>(move |params, _| {
8709 assert_eq!(
8710 params.text_document_position.text_document.uri,
8711 lsp::Url::from_file_path(path).unwrap()
8712 );
8713 assert_eq!(
8714 params.text_document_position.position,
8715 lsp::Position::new(position.row, position.column)
8716 );
8717 Some(lsp::CompletionResponse::Array(
8718 completions
8719 .iter()
8720 .map(|(range, new_text)| lsp::CompletionItem {
8721 label: new_text.to_string(),
8722 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8723 range: lsp::Range::new(
8724 lsp::Position::new(range.start.row, range.start.column),
8725 lsp::Position::new(range.start.row, range.start.column),
8726 ),
8727 new_text: new_text.to_string(),
8728 })),
8729 ..Default::default()
8730 })
8731 .collect(),
8732 ))
8733 })
8734 .next()
8735 .await;
8736 }
8737
8738 async fn handle_resolve_completion_request(
8739 fake: &mut FakeLanguageServer,
8740 edit: Option<(Range<Point>, &'static str)>,
8741 ) {
8742 fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_, _| {
8743 lsp::CompletionItem {
8744 additional_text_edits: edit.clone().map(|(range, new_text)| {
8745 vec![lsp::TextEdit::new(
8746 lsp::Range::new(
8747 lsp::Position::new(range.start.row, range.start.column),
8748 lsp::Position::new(range.end.row, range.end.column),
8749 ),
8750 new_text.to_string(),
8751 )]
8752 }),
8753 ..Default::default()
8754 }
8755 })
8756 .next()
8757 .await;
8758 }
8759 }
8760
8761 #[gpui::test]
8762 async fn test_toggle_comment(cx: &mut gpui::TestAppContext) {
8763 cx.update(populate_settings);
8764 let language = Arc::new(Language::new(
8765 LanguageConfig {
8766 line_comment: Some("// ".to_string()),
8767 ..Default::default()
8768 },
8769 Some(tree_sitter_rust::language()),
8770 ));
8771
8772 let text = "
8773 fn a() {
8774 //b();
8775 // c();
8776 // d();
8777 }
8778 "
8779 .unindent();
8780
8781 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8782 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8783 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
8784
8785 view.update(cx, |editor, cx| {
8786 // If multiple selections intersect a line, the line is only
8787 // toggled once.
8788 editor.select_display_ranges(
8789 &[
8790 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8791 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8792 ],
8793 cx,
8794 );
8795 editor.toggle_comments(&ToggleComments, cx);
8796 assert_eq!(
8797 editor.text(cx),
8798 "
8799 fn a() {
8800 b();
8801 c();
8802 d();
8803 }
8804 "
8805 .unindent()
8806 );
8807
8808 // The comment prefix is inserted at the same column for every line
8809 // in a selection.
8810 editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8811 editor.toggle_comments(&ToggleComments, cx);
8812 assert_eq!(
8813 editor.text(cx),
8814 "
8815 fn a() {
8816 // b();
8817 // c();
8818 // d();
8819 }
8820 "
8821 .unindent()
8822 );
8823
8824 // If a selection ends at the beginning of a line, that line is not toggled.
8825 editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8826 editor.toggle_comments(&ToggleComments, cx);
8827 assert_eq!(
8828 editor.text(cx),
8829 "
8830 fn a() {
8831 // b();
8832 c();
8833 // d();
8834 }
8835 "
8836 .unindent()
8837 );
8838 });
8839 }
8840
8841 #[gpui::test]
8842 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8843 populate_settings(cx);
8844 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8845 let multibuffer = cx.add_model(|cx| {
8846 let mut multibuffer = MultiBuffer::new(0);
8847 multibuffer.push_excerpts(
8848 buffer.clone(),
8849 [
8850 Point::new(0, 0)..Point::new(0, 4),
8851 Point::new(1, 0)..Point::new(1, 4),
8852 ],
8853 cx,
8854 );
8855 multibuffer
8856 });
8857
8858 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
8859
8860 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8861 view.update(cx, |view, cx| {
8862 assert_eq!(view.text(cx), "aaaa\nbbbb");
8863 view.select_ranges(
8864 [
8865 Point::new(0, 0)..Point::new(0, 0),
8866 Point::new(1, 0)..Point::new(1, 0),
8867 ],
8868 None,
8869 cx,
8870 );
8871
8872 view.handle_input(&Input("X".to_string()), cx);
8873 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
8874 assert_eq!(
8875 view.selected_ranges(cx),
8876 [
8877 Point::new(0, 1)..Point::new(0, 1),
8878 Point::new(1, 1)..Point::new(1, 1),
8879 ]
8880 )
8881 });
8882 }
8883
8884 #[gpui::test]
8885 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
8886 populate_settings(cx);
8887 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8888 let multibuffer = cx.add_model(|cx| {
8889 let mut multibuffer = MultiBuffer::new(0);
8890 multibuffer.push_excerpts(
8891 buffer,
8892 [
8893 Point::new(0, 0)..Point::new(1, 4),
8894 Point::new(1, 0)..Point::new(2, 4),
8895 ],
8896 cx,
8897 );
8898 multibuffer
8899 });
8900
8901 assert_eq!(
8902 multibuffer.read(cx).read(cx).text(),
8903 "aaaa\nbbbb\nbbbb\ncccc"
8904 );
8905
8906 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(multibuffer, cx));
8907 view.update(cx, |view, cx| {
8908 view.select_ranges(
8909 [
8910 Point::new(1, 1)..Point::new(1, 1),
8911 Point::new(2, 3)..Point::new(2, 3),
8912 ],
8913 None,
8914 cx,
8915 );
8916
8917 view.handle_input(&Input("X".to_string()), cx);
8918 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
8919 assert_eq!(
8920 view.selected_ranges(cx),
8921 [
8922 Point::new(1, 2)..Point::new(1, 2),
8923 Point::new(2, 5)..Point::new(2, 5),
8924 ]
8925 );
8926
8927 view.newline(&Newline, cx);
8928 assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
8929 assert_eq!(
8930 view.selected_ranges(cx),
8931 [
8932 Point::new(2, 0)..Point::new(2, 0),
8933 Point::new(6, 0)..Point::new(6, 0),
8934 ]
8935 );
8936 });
8937 }
8938
8939 #[gpui::test]
8940 fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
8941 populate_settings(cx);
8942 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8943 let mut excerpt1_id = None;
8944 let multibuffer = cx.add_model(|cx| {
8945 let mut multibuffer = MultiBuffer::new(0);
8946 excerpt1_id = multibuffer
8947 .push_excerpts(
8948 buffer.clone(),
8949 [
8950 Point::new(0, 0)..Point::new(1, 4),
8951 Point::new(1, 0)..Point::new(2, 4),
8952 ],
8953 cx,
8954 )
8955 .into_iter()
8956 .next();
8957 multibuffer
8958 });
8959 assert_eq!(
8960 multibuffer.read(cx).read(cx).text(),
8961 "aaaa\nbbbb\nbbbb\ncccc"
8962 );
8963 let (_, editor) = cx.add_window(Default::default(), |cx| {
8964 let mut editor = build_editor(multibuffer.clone(), cx);
8965 let snapshot = editor.snapshot(cx);
8966 editor.select_ranges([Point::new(1, 3)..Point::new(1, 3)], None, cx);
8967 editor.begin_selection(Point::new(2, 1).to_display_point(&snapshot), true, 1, cx);
8968 assert_eq!(
8969 editor.selected_ranges(cx),
8970 [
8971 Point::new(1, 3)..Point::new(1, 3),
8972 Point::new(2, 1)..Point::new(2, 1),
8973 ]
8974 );
8975 editor
8976 });
8977
8978 // Refreshing selections is a no-op when excerpts haven't changed.
8979 editor.update(cx, |editor, cx| {
8980 editor.refresh_selections(cx);
8981 assert_eq!(
8982 editor.selected_ranges(cx),
8983 [
8984 Point::new(1, 3)..Point::new(1, 3),
8985 Point::new(2, 1)..Point::new(2, 1),
8986 ]
8987 );
8988 });
8989
8990 multibuffer.update(cx, |multibuffer, cx| {
8991 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
8992 });
8993 editor.update(cx, |editor, cx| {
8994 // Removing an excerpt causes the first selection to become degenerate.
8995 assert_eq!(
8996 editor.selected_ranges(cx),
8997 [
8998 Point::new(0, 0)..Point::new(0, 0),
8999 Point::new(0, 1)..Point::new(0, 1)
9000 ]
9001 );
9002
9003 // Refreshing selections will relocate the first selection to the original buffer
9004 // location.
9005 editor.refresh_selections(cx);
9006 assert_eq!(
9007 editor.selected_ranges(cx),
9008 [
9009 Point::new(0, 1)..Point::new(0, 1),
9010 Point::new(0, 3)..Point::new(0, 3)
9011 ]
9012 );
9013 assert!(editor.pending_selection.is_some());
9014 });
9015 }
9016
9017 #[gpui::test]
9018 fn test_refresh_selections_while_selecting_with_mouse(cx: &mut gpui::MutableAppContext) {
9019 populate_settings(cx);
9020 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
9021 let mut excerpt1_id = None;
9022 let multibuffer = cx.add_model(|cx| {
9023 let mut multibuffer = MultiBuffer::new(0);
9024 excerpt1_id = multibuffer
9025 .push_excerpts(
9026 buffer.clone(),
9027 [
9028 Point::new(0, 0)..Point::new(1, 4),
9029 Point::new(1, 0)..Point::new(2, 4),
9030 ],
9031 cx,
9032 )
9033 .into_iter()
9034 .next();
9035 multibuffer
9036 });
9037 assert_eq!(
9038 multibuffer.read(cx).read(cx).text(),
9039 "aaaa\nbbbb\nbbbb\ncccc"
9040 );
9041 let (_, editor) = cx.add_window(Default::default(), |cx| {
9042 let mut editor = build_editor(multibuffer.clone(), cx);
9043 let snapshot = editor.snapshot(cx);
9044 editor.begin_selection(Point::new(1, 3).to_display_point(&snapshot), false, 1, cx);
9045 assert_eq!(
9046 editor.selected_ranges(cx),
9047 [Point::new(1, 3)..Point::new(1, 3)]
9048 );
9049 editor
9050 });
9051
9052 multibuffer.update(cx, |multibuffer, cx| {
9053 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
9054 });
9055 editor.update(cx, |editor, cx| {
9056 assert_eq!(
9057 editor.selected_ranges(cx),
9058 [Point::new(0, 0)..Point::new(0, 0)]
9059 );
9060
9061 // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
9062 editor.refresh_selections(cx);
9063 assert_eq!(
9064 editor.selected_ranges(cx),
9065 [Point::new(0, 3)..Point::new(0, 3)]
9066 );
9067 assert!(editor.pending_selection.is_some());
9068 });
9069 }
9070
9071 #[gpui::test]
9072 async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
9073 cx.update(populate_settings);
9074 let language = Arc::new(Language::new(
9075 LanguageConfig {
9076 brackets: vec![
9077 BracketPair {
9078 start: "{".to_string(),
9079 end: "}".to_string(),
9080 close: true,
9081 newline: true,
9082 },
9083 BracketPair {
9084 start: "/* ".to_string(),
9085 end: " */".to_string(),
9086 close: true,
9087 newline: true,
9088 },
9089 ],
9090 ..Default::default()
9091 },
9092 Some(tree_sitter_rust::language()),
9093 ));
9094
9095 let text = concat!(
9096 "{ }\n", // Suppress rustfmt
9097 " x\n", //
9098 " /* */\n", //
9099 "x\n", //
9100 "{{} }\n", //
9101 );
9102
9103 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
9104 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
9105 let (_, view) = cx.add_window(|cx| build_editor(buffer, cx));
9106 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
9107 .await;
9108
9109 view.update(cx, |view, cx| {
9110 view.select_display_ranges(
9111 &[
9112 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
9113 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
9114 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
9115 ],
9116 cx,
9117 );
9118 view.newline(&Newline, cx);
9119
9120 assert_eq!(
9121 view.buffer().read(cx).read(cx).text(),
9122 concat!(
9123 "{ \n", // Suppress rustfmt
9124 "\n", //
9125 "}\n", //
9126 " x\n", //
9127 " /* \n", //
9128 " \n", //
9129 " */\n", //
9130 "x\n", //
9131 "{{} \n", //
9132 "}\n", //
9133 )
9134 );
9135 });
9136 }
9137
9138 #[gpui::test]
9139 fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
9140 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9141 populate_settings(cx);
9142 let (_, editor) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9143
9144 editor.update(cx, |editor, cx| {
9145 struct Type1;
9146 struct Type2;
9147
9148 let buffer = buffer.read(cx).snapshot(cx);
9149
9150 let anchor_range = |range: Range<Point>| {
9151 buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
9152 };
9153
9154 editor.highlight_background::<Type1>(
9155 vec![
9156 anchor_range(Point::new(2, 1)..Point::new(2, 3)),
9157 anchor_range(Point::new(4, 2)..Point::new(4, 4)),
9158 anchor_range(Point::new(6, 3)..Point::new(6, 5)),
9159 anchor_range(Point::new(8, 4)..Point::new(8, 6)),
9160 ],
9161 Color::red(),
9162 cx,
9163 );
9164 editor.highlight_background::<Type2>(
9165 vec![
9166 anchor_range(Point::new(3, 2)..Point::new(3, 5)),
9167 anchor_range(Point::new(5, 3)..Point::new(5, 6)),
9168 anchor_range(Point::new(7, 4)..Point::new(7, 7)),
9169 anchor_range(Point::new(9, 5)..Point::new(9, 8)),
9170 ],
9171 Color::green(),
9172 cx,
9173 );
9174
9175 let snapshot = editor.snapshot(cx);
9176 let mut highlighted_ranges = editor.background_highlights_in_range(
9177 anchor_range(Point::new(3, 4)..Point::new(7, 4)),
9178 &snapshot,
9179 );
9180 // Enforce a consistent ordering based on color without relying on the ordering of the
9181 // highlight's `TypeId` which is non-deterministic.
9182 highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
9183 assert_eq!(
9184 highlighted_ranges,
9185 &[
9186 (
9187 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
9188 Color::green(),
9189 ),
9190 (
9191 DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
9192 Color::green(),
9193 ),
9194 (
9195 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
9196 Color::red(),
9197 ),
9198 (
9199 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9200 Color::red(),
9201 ),
9202 ]
9203 );
9204 assert_eq!(
9205 editor.background_highlights_in_range(
9206 anchor_range(Point::new(5, 6)..Point::new(6, 4)),
9207 &snapshot,
9208 ),
9209 &[(
9210 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
9211 Color::red(),
9212 )]
9213 );
9214 });
9215 }
9216
9217 #[gpui::test]
9218 fn test_following(cx: &mut gpui::MutableAppContext) {
9219 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
9220 populate_settings(cx);
9221
9222 let (_, leader) = cx.add_window(Default::default(), |cx| build_editor(buffer.clone(), cx));
9223 let (_, follower) = cx.add_window(
9224 WindowOptions {
9225 bounds: WindowBounds::Fixed(RectF::from_points(vec2f(0., 0.), vec2f(10., 80.))),
9226 ..Default::default()
9227 },
9228 |cx| build_editor(buffer.clone(), cx),
9229 );
9230
9231 let pending_update = Rc::new(RefCell::new(None));
9232 follower.update(cx, {
9233 let update = pending_update.clone();
9234 |_, cx| {
9235 cx.subscribe(&leader, move |_, leader, event, cx| {
9236 leader
9237 .read(cx)
9238 .add_event_to_update_proto(event, &mut *update.borrow_mut(), cx);
9239 })
9240 .detach();
9241 }
9242 });
9243
9244 // Update the selections only
9245 leader.update(cx, |leader, cx| {
9246 leader.select_ranges([1..1], None, cx);
9247 });
9248 follower.update(cx, |follower, cx| {
9249 follower
9250 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9251 .unwrap();
9252 });
9253 assert_eq!(follower.read(cx).selected_ranges(cx), vec![1..1]);
9254
9255 // Update the scroll position only
9256 leader.update(cx, |leader, cx| {
9257 leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9258 });
9259 follower.update(cx, |follower, cx| {
9260 follower
9261 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9262 .unwrap();
9263 });
9264 assert_eq!(
9265 follower.update(cx, |follower, cx| follower.scroll_position(cx)),
9266 vec2f(1.5, 3.5)
9267 );
9268
9269 // Update the selections and scroll position
9270 leader.update(cx, |leader, cx| {
9271 leader.select_ranges([0..0], None, cx);
9272 leader.request_autoscroll(Autoscroll::Newest, cx);
9273 leader.set_scroll_position(vec2f(1.5, 3.5), cx);
9274 });
9275 follower.update(cx, |follower, cx| {
9276 let initial_scroll_position = follower.scroll_position(cx);
9277 follower
9278 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9279 .unwrap();
9280 assert_eq!(follower.scroll_position(cx), initial_scroll_position);
9281 assert!(follower.autoscroll_request.is_some());
9282 });
9283 assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0]);
9284
9285 // Creating a pending selection that precedes another selection
9286 leader.update(cx, |leader, cx| {
9287 leader.select_ranges([1..1], None, cx);
9288 leader.begin_selection(DisplayPoint::new(0, 0), true, 1, cx);
9289 });
9290 follower.update(cx, |follower, cx| {
9291 follower
9292 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9293 .unwrap();
9294 });
9295 assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..0, 1..1]);
9296
9297 // Extend the pending selection so that it surrounds another selection
9298 leader.update(cx, |leader, cx| {
9299 leader.extend_selection(DisplayPoint::new(0, 2), 1, cx);
9300 });
9301 follower.update(cx, |follower, cx| {
9302 follower
9303 .apply_update_proto(pending_update.borrow_mut().take().unwrap(), cx)
9304 .unwrap();
9305 });
9306 assert_eq!(follower.read(cx).selected_ranges(cx), vec![0..2]);
9307 }
9308
9309 #[test]
9310 fn test_combine_syntax_and_fuzzy_match_highlights() {
9311 let string = "abcdefghijklmnop";
9312 let syntax_ranges = [
9313 (
9314 0..3,
9315 HighlightStyle {
9316 color: Some(Color::red()),
9317 ..Default::default()
9318 },
9319 ),
9320 (
9321 4..8,
9322 HighlightStyle {
9323 color: Some(Color::green()),
9324 ..Default::default()
9325 },
9326 ),
9327 ];
9328 let match_indices = [4, 6, 7, 8];
9329 assert_eq!(
9330 combine_syntax_and_fuzzy_match_highlights(
9331 &string,
9332 Default::default(),
9333 syntax_ranges.into_iter(),
9334 &match_indices,
9335 ),
9336 &[
9337 (
9338 0..3,
9339 HighlightStyle {
9340 color: Some(Color::red()),
9341 ..Default::default()
9342 },
9343 ),
9344 (
9345 4..5,
9346 HighlightStyle {
9347 color: Some(Color::green()),
9348 weight: Some(fonts::Weight::BOLD),
9349 ..Default::default()
9350 },
9351 ),
9352 (
9353 5..6,
9354 HighlightStyle {
9355 color: Some(Color::green()),
9356 ..Default::default()
9357 },
9358 ),
9359 (
9360 6..8,
9361 HighlightStyle {
9362 color: Some(Color::green()),
9363 weight: Some(fonts::Weight::BOLD),
9364 ..Default::default()
9365 },
9366 ),
9367 (
9368 8..9,
9369 HighlightStyle {
9370 weight: Some(fonts::Weight::BOLD),
9371 ..Default::default()
9372 },
9373 ),
9374 ]
9375 );
9376 }
9377
9378 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
9379 let point = DisplayPoint::new(row as u32, column as u32);
9380 point..point
9381 }
9382
9383 fn build_editor(buffer: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Editor>) -> Editor {
9384 Editor::new(EditorMode::Full, buffer, None, None, cx)
9385 }
9386
9387 fn populate_settings(cx: &mut gpui::MutableAppContext) {
9388 let settings = Settings::test(cx);
9389 cx.set_global(settings);
9390 }
9391
9392 fn assert_selection_ranges(
9393 marked_text: &str,
9394 selection_marker_pairs: Vec<(char, char)>,
9395 view: &mut Editor,
9396 cx: &mut ViewContext<Editor>,
9397 ) {
9398 let snapshot = view.snapshot(cx).display_snapshot;
9399 let mut marker_chars = Vec::new();
9400 for (start, end) in selection_marker_pairs.iter() {
9401 marker_chars.push(*start);
9402 marker_chars.push(*end);
9403 }
9404 let (_, markers) = marked_text_by(marked_text, marker_chars);
9405 let asserted_ranges: Vec<Range<DisplayPoint>> = selection_marker_pairs
9406 .iter()
9407 .map(|(start, end)| {
9408 let start = markers.get(start).unwrap()[0].to_display_point(&snapshot);
9409 let end = markers.get(end).unwrap()[0].to_display_point(&snapshot);
9410 start..end
9411 })
9412 .collect();
9413 assert_eq!(
9414 view.selected_display_ranges(cx),
9415 &asserted_ranges[..],
9416 "Assert selections are {}",
9417 marked_text
9418 );
9419 }
9420}
9421
9422trait RangeExt<T> {
9423 fn sorted(&self) -> Range<T>;
9424 fn to_inclusive(&self) -> RangeInclusive<T>;
9425}
9426
9427impl<T: Ord + Clone> RangeExt<T> for Range<T> {
9428 fn sorted(&self) -> Self {
9429 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
9430 }
9431
9432 fn to_inclusive(&self) -> RangeInclusive<T> {
9433 self.start.clone()..=self.end.clone()
9434 }
9435}