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