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