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