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