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