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