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