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