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