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