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