1pub mod display_map;
2mod element;
3pub mod items;
4pub mod movement;
5mod multi_buffer;
6
7#[cfg(test)]
8mod test;
9
10use aho_corasick::AhoCorasick;
11use anyhow::Result;
12use clock::ReplicaId;
13use collections::{BTreeMap, HashMap, HashSet};
14pub use display_map::DisplayPoint;
15use display_map::*;
16pub use element::*;
17use fuzzy::{StringMatch, StringMatchCandidate};
18use gpui::{
19 action,
20 color::Color,
21 elements::*,
22 executor,
23 fonts::{self, HighlightStyle, TextStyle},
24 geometry::vector::{vec2f, Vector2F},
25 keymap::Binding,
26 platform::CursorStyle,
27 text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
28 MutableAppContext, RenderContext, Task, View, ViewContext, WeakModelHandle, WeakViewHandle,
29};
30use items::BufferItemHandle;
31use itertools::Itertools as _;
32use language::{
33 AnchorRangeExt as _, BracketPair, Buffer, 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(insertion_point..range_to_move.end)
2609 .next()
2610 .is_none()
2611 {
2612 let text = buffer
2613 .text_for_range(range_to_move.clone())
2614 .flat_map(|s| s.chars())
2615 .skip(1)
2616 .chain(['\n'])
2617 .collect::<String>();
2618
2619 edits.push((
2620 buffer.anchor_after(range_to_move.start)
2621 ..buffer.anchor_before(range_to_move.end),
2622 String::new(),
2623 ));
2624 let insertion_anchor = buffer.anchor_after(insertion_point);
2625 edits.push((insertion_anchor.clone()..insertion_anchor, text));
2626
2627 let row_delta = range_to_move.start.row - insertion_point.row + 1;
2628
2629 // Move selections up
2630 new_selections.extend(contiguous_row_selections.drain(..).map(
2631 |mut selection| {
2632 selection.start.row -= row_delta;
2633 selection.end.row -= row_delta;
2634 selection
2635 },
2636 ));
2637
2638 // Move folds up
2639 unfold_ranges.push(range_to_move.clone());
2640 for fold in display_map.folds_in_range(
2641 buffer.anchor_before(range_to_move.start)
2642 ..buffer.anchor_after(range_to_move.end),
2643 ) {
2644 let mut start = fold.start.to_point(&buffer);
2645 let mut end = fold.end.to_point(&buffer);
2646 start.row -= row_delta;
2647 end.row -= row_delta;
2648 refold_ranges.push(start..end);
2649 }
2650 }
2651 }
2652
2653 // If we didn't move line(s), preserve the existing selections
2654 new_selections.extend(contiguous_row_selections.drain(..));
2655 }
2656
2657 self.start_transaction(cx);
2658 self.unfold_ranges(unfold_ranges, cx);
2659 self.buffer.update(cx, |buffer, cx| {
2660 for (range, text) in edits {
2661 buffer.edit([range], text, cx);
2662 }
2663 });
2664 self.fold_ranges(refold_ranges, cx);
2665 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2666 self.end_transaction(cx);
2667 }
2668
2669 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
2670 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2671 let buffer = self.buffer.read(cx).snapshot(cx);
2672
2673 let mut edits = Vec::new();
2674 let mut unfold_ranges = Vec::new();
2675 let mut refold_ranges = Vec::new();
2676
2677 let selections = self.local_selections::<Point>(cx);
2678 let mut selections = selections.iter().peekable();
2679 let mut contiguous_row_selections = Vec::new();
2680 let mut new_selections = Vec::new();
2681
2682 while let Some(selection) = selections.next() {
2683 // Find all the selections that span a contiguous row range
2684 contiguous_row_selections.push(selection.clone());
2685 let start_row = selection.start.row;
2686 let mut end_row = if selection.end.column > 0 || selection.is_empty() {
2687 display_map.next_line_boundary(selection.end).0.row + 1
2688 } else {
2689 selection.end.row
2690 };
2691
2692 while let Some(next_selection) = selections.peek() {
2693 if next_selection.start.row <= end_row {
2694 end_row = if next_selection.end.column > 0 || next_selection.is_empty() {
2695 display_map.next_line_boundary(next_selection.end).0.row + 1
2696 } else {
2697 next_selection.end.row
2698 };
2699 contiguous_row_selections.push(selections.next().unwrap().clone());
2700 } else {
2701 break;
2702 }
2703 }
2704
2705 // Move the text spanned by the row range to be after the last line of the row range
2706 if end_row <= buffer.max_point().row {
2707 let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
2708 let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
2709
2710 // Don't move lines across excerpt boundaries
2711 if buffer
2712 .excerpt_boundaries_in_range(range_to_move.start..insertion_point)
2713 .next()
2714 .is_none()
2715 {
2716 let mut text = String::from("\n");
2717 text.extend(buffer.text_for_range(range_to_move.clone()));
2718 text.pop(); // Drop trailing newline
2719 edits.push((
2720 buffer.anchor_after(range_to_move.start)
2721 ..buffer.anchor_before(range_to_move.end),
2722 String::new(),
2723 ));
2724 let insertion_anchor = buffer.anchor_after(insertion_point);
2725 edits.push((insertion_anchor.clone()..insertion_anchor, text));
2726
2727 let row_delta = insertion_point.row - range_to_move.end.row + 1;
2728
2729 // Move selections down
2730 new_selections.extend(contiguous_row_selections.drain(..).map(
2731 |mut selection| {
2732 selection.start.row += row_delta;
2733 selection.end.row += row_delta;
2734 selection
2735 },
2736 ));
2737
2738 // Move folds down
2739 unfold_ranges.push(range_to_move.clone());
2740 for fold in display_map.folds_in_range(
2741 buffer.anchor_before(range_to_move.start)
2742 ..buffer.anchor_after(range_to_move.end),
2743 ) {
2744 let mut start = fold.start.to_point(&buffer);
2745 let mut end = fold.end.to_point(&buffer);
2746 start.row += row_delta;
2747 end.row += row_delta;
2748 refold_ranges.push(start..end);
2749 }
2750 }
2751 }
2752
2753 // If we didn't move line(s), preserve the existing selections
2754 new_selections.extend(contiguous_row_selections.drain(..));
2755 }
2756
2757 self.start_transaction(cx);
2758 self.unfold_ranges(unfold_ranges, cx);
2759 self.buffer.update(cx, |buffer, cx| {
2760 for (range, text) in edits {
2761 buffer.edit([range], text, cx);
2762 }
2763 });
2764 self.fold_ranges(refold_ranges, cx);
2765 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2766 self.end_transaction(cx);
2767 }
2768
2769 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
2770 self.start_transaction(cx);
2771 let mut text = String::new();
2772 let mut selections = self.local_selections::<Point>(cx);
2773 let mut clipboard_selections = Vec::with_capacity(selections.len());
2774 {
2775 let buffer = self.buffer.read(cx).read(cx);
2776 let max_point = buffer.max_point();
2777 for selection in &mut selections {
2778 let is_entire_line = selection.is_empty();
2779 if is_entire_line {
2780 selection.start = Point::new(selection.start.row, 0);
2781 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
2782 selection.goal = SelectionGoal::None;
2783 }
2784 let mut len = 0;
2785 for chunk in buffer.text_for_range(selection.start..selection.end) {
2786 text.push_str(chunk);
2787 len += chunk.len();
2788 }
2789 clipboard_selections.push(ClipboardSelection {
2790 len,
2791 is_entire_line,
2792 });
2793 }
2794 }
2795 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2796 self.insert("", cx);
2797 self.end_transaction(cx);
2798
2799 cx.as_mut()
2800 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
2801 }
2802
2803 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
2804 let selections = self.local_selections::<Point>(cx);
2805 let mut text = String::new();
2806 let mut clipboard_selections = Vec::with_capacity(selections.len());
2807 {
2808 let buffer = self.buffer.read(cx).read(cx);
2809 let max_point = buffer.max_point();
2810 for selection in selections.iter() {
2811 let mut start = selection.start;
2812 let mut end = selection.end;
2813 let is_entire_line = selection.is_empty();
2814 if is_entire_line {
2815 start = Point::new(start.row, 0);
2816 end = cmp::min(max_point, Point::new(start.row + 1, 0));
2817 }
2818 let mut len = 0;
2819 for chunk in buffer.text_for_range(start..end) {
2820 text.push_str(chunk);
2821 len += chunk.len();
2822 }
2823 clipboard_selections.push(ClipboardSelection {
2824 len,
2825 is_entire_line,
2826 });
2827 }
2828 }
2829
2830 cx.as_mut()
2831 .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
2832 }
2833
2834 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
2835 if let Some(item) = cx.as_mut().read_from_clipboard() {
2836 let clipboard_text = item.text();
2837 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
2838 let mut selections = self.local_selections::<usize>(cx);
2839 let all_selections_were_entire_line =
2840 clipboard_selections.iter().all(|s| s.is_entire_line);
2841 if clipboard_selections.len() != selections.len() {
2842 clipboard_selections.clear();
2843 }
2844
2845 let mut delta = 0_isize;
2846 let mut start_offset = 0;
2847 for (i, selection) in selections.iter_mut().enumerate() {
2848 let to_insert;
2849 let entire_line;
2850 if let Some(clipboard_selection) = clipboard_selections.get(i) {
2851 let end_offset = start_offset + clipboard_selection.len;
2852 to_insert = &clipboard_text[start_offset..end_offset];
2853 entire_line = clipboard_selection.is_entire_line;
2854 start_offset = end_offset
2855 } else {
2856 to_insert = clipboard_text.as_str();
2857 entire_line = all_selections_were_entire_line;
2858 }
2859
2860 selection.start = (selection.start as isize + delta) as usize;
2861 selection.end = (selection.end as isize + delta) as usize;
2862
2863 self.buffer.update(cx, |buffer, cx| {
2864 // If the corresponding selection was empty when this slice of the
2865 // clipboard text was written, then the entire line containing the
2866 // selection was copied. If this selection is also currently empty,
2867 // then paste the line before the current line of the buffer.
2868 let range = if selection.is_empty() && entire_line {
2869 let column = selection.start.to_point(&buffer.read(cx)).column as usize;
2870 let line_start = selection.start - column;
2871 line_start..line_start
2872 } else {
2873 selection.start..selection.end
2874 };
2875
2876 delta += to_insert.len() as isize - range.len() as isize;
2877 buffer.edit([range], to_insert, cx);
2878 selection.start += to_insert.len();
2879 selection.end = selection.start;
2880 });
2881 }
2882 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2883 } else {
2884 self.insert(clipboard_text, cx);
2885 }
2886 }
2887 }
2888
2889 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
2890 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
2891 if let Some((selections, _)) = self.selection_history.get(&tx_id).cloned() {
2892 self.set_selections(selections, cx);
2893 }
2894 self.request_autoscroll(Autoscroll::Fit, cx);
2895 }
2896 }
2897
2898 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
2899 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
2900 if let Some((_, Some(selections))) = self.selection_history.get(&tx_id).cloned() {
2901 self.set_selections(selections, cx);
2902 }
2903 self.request_autoscroll(Autoscroll::Fit, cx);
2904 }
2905 }
2906
2907 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
2908 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2909 let mut selections = self.local_selections::<Point>(cx);
2910 for selection in &mut selections {
2911 let start = selection.start.to_display_point(&display_map);
2912 let end = selection.end.to_display_point(&display_map);
2913
2914 if start != end {
2915 selection.end = selection.start.clone();
2916 } else {
2917 let cursor = movement::left(&display_map, start)
2918 .unwrap()
2919 .to_point(&display_map);
2920 selection.start = cursor.clone();
2921 selection.end = cursor;
2922 }
2923 selection.reversed = false;
2924 selection.goal = SelectionGoal::None;
2925 }
2926 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2927 }
2928
2929 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2930 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2931 let mut selections = self.local_selections::<Point>(cx);
2932 for selection in &mut selections {
2933 let head = selection.head().to_display_point(&display_map);
2934 let cursor = movement::left(&display_map, head)
2935 .unwrap()
2936 .to_point(&display_map);
2937 selection.set_head(cursor);
2938 selection.goal = SelectionGoal::None;
2939 }
2940 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2941 }
2942
2943 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2944 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2945 let mut selections = self.local_selections::<Point>(cx);
2946 for selection in &mut selections {
2947 let start = selection.start.to_display_point(&display_map);
2948 let end = selection.end.to_display_point(&display_map);
2949
2950 if start != end {
2951 selection.start = selection.end.clone();
2952 } else {
2953 let cursor = movement::right(&display_map, end)
2954 .unwrap()
2955 .to_point(&display_map);
2956 selection.start = cursor;
2957 selection.end = cursor;
2958 }
2959 selection.reversed = false;
2960 selection.goal = SelectionGoal::None;
2961 }
2962 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2963 }
2964
2965 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2966 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2967 let mut selections = self.local_selections::<Point>(cx);
2968 for selection in &mut selections {
2969 let head = selection.head().to_display_point(&display_map);
2970 let cursor = movement::right(&display_map, head)
2971 .unwrap()
2972 .to_point(&display_map);
2973 selection.set_head(cursor);
2974 selection.goal = SelectionGoal::None;
2975 }
2976 self.update_selections(selections, Some(Autoscroll::Fit), cx);
2977 }
2978
2979 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2980 if let Some(context_menu) = self.context_menu.as_mut() {
2981 if context_menu.select_prev(cx) {
2982 return;
2983 }
2984 }
2985
2986 if matches!(self.mode, EditorMode::SingleLine) {
2987 cx.propagate_action();
2988 return;
2989 }
2990
2991 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2992 let mut selections = self.local_selections::<Point>(cx);
2993 for selection in &mut selections {
2994 let start = selection.start.to_display_point(&display_map);
2995 let end = selection.end.to_display_point(&display_map);
2996 if start != end {
2997 selection.goal = SelectionGoal::None;
2998 }
2999
3000 let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
3001 let cursor = start.to_point(&display_map);
3002 selection.start = cursor;
3003 selection.end = cursor;
3004 selection.goal = goal;
3005 selection.reversed = false;
3006 }
3007 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3008 }
3009
3010 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
3011 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3012 let mut selections = self.local_selections::<Point>(cx);
3013 for selection in &mut selections {
3014 let head = selection.head().to_display_point(&display_map);
3015 let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
3016 let cursor = head.to_point(&display_map);
3017 selection.set_head(cursor);
3018 selection.goal = goal;
3019 }
3020 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3021 }
3022
3023 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
3024 if let Some(context_menu) = self.context_menu.as_mut() {
3025 if context_menu.select_next(cx) {
3026 return;
3027 }
3028 }
3029
3030 if matches!(self.mode, EditorMode::SingleLine) {
3031 cx.propagate_action();
3032 return;
3033 }
3034
3035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3036 let mut selections = self.local_selections::<Point>(cx);
3037 for selection in &mut selections {
3038 let start = selection.start.to_display_point(&display_map);
3039 let end = selection.end.to_display_point(&display_map);
3040 if start != end {
3041 selection.goal = SelectionGoal::None;
3042 }
3043
3044 let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
3045 let cursor = start.to_point(&display_map);
3046 selection.start = cursor;
3047 selection.end = cursor;
3048 selection.goal = goal;
3049 selection.reversed = false;
3050 }
3051 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3052 }
3053
3054 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
3055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3056 let mut selections = self.local_selections::<Point>(cx);
3057 for selection in &mut selections {
3058 let head = selection.head().to_display_point(&display_map);
3059 let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
3060 let cursor = head.to_point(&display_map);
3061 selection.set_head(cursor);
3062 selection.goal = goal;
3063 }
3064 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3065 }
3066
3067 pub fn move_to_previous_word_boundary(
3068 &mut self,
3069 _: &MoveToPreviousWordBoundary,
3070 cx: &mut ViewContext<Self>,
3071 ) {
3072 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3073 let mut selections = self.local_selections::<Point>(cx);
3074 for selection in &mut selections {
3075 let head = selection.head().to_display_point(&display_map);
3076 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
3077 selection.start = cursor.clone();
3078 selection.end = cursor;
3079 selection.reversed = false;
3080 selection.goal = SelectionGoal::None;
3081 }
3082 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3083 }
3084
3085 pub fn select_to_previous_word_boundary(
3086 &mut self,
3087 _: &SelectToPreviousWordBoundary,
3088 cx: &mut ViewContext<Self>,
3089 ) {
3090 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3091 let mut selections = self.local_selections::<Point>(cx);
3092 for selection in &mut selections {
3093 let head = selection.head().to_display_point(&display_map);
3094 let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
3095 selection.set_head(cursor);
3096 selection.goal = SelectionGoal::None;
3097 }
3098 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3099 }
3100
3101 pub fn delete_to_previous_word_boundary(
3102 &mut self,
3103 _: &DeleteToPreviousWordBoundary,
3104 cx: &mut ViewContext<Self>,
3105 ) {
3106 self.start_transaction(cx);
3107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3108 let mut selections = self.local_selections::<Point>(cx);
3109 for selection in &mut selections {
3110 if selection.is_empty() {
3111 let head = selection.head().to_display_point(&display_map);
3112 let cursor =
3113 movement::prev_word_boundary(&display_map, head).to_point(&display_map);
3114 selection.set_head(cursor);
3115 selection.goal = SelectionGoal::None;
3116 }
3117 }
3118 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3119 self.insert("", cx);
3120 self.end_transaction(cx);
3121 }
3122
3123 pub fn move_to_next_word_boundary(
3124 &mut self,
3125 _: &MoveToNextWordBoundary,
3126 cx: &mut ViewContext<Self>,
3127 ) {
3128 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3129 let mut selections = self.local_selections::<Point>(cx);
3130 for selection in &mut selections {
3131 let head = selection.head().to_display_point(&display_map);
3132 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
3133 selection.start = cursor;
3134 selection.end = cursor;
3135 selection.reversed = false;
3136 selection.goal = SelectionGoal::None;
3137 }
3138 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3139 }
3140
3141 pub fn select_to_next_word_boundary(
3142 &mut self,
3143 _: &SelectToNextWordBoundary,
3144 cx: &mut ViewContext<Self>,
3145 ) {
3146 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3147 let mut selections = self.local_selections::<Point>(cx);
3148 for selection in &mut selections {
3149 let head = selection.head().to_display_point(&display_map);
3150 let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
3151 selection.set_head(cursor);
3152 selection.goal = SelectionGoal::None;
3153 }
3154 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3155 }
3156
3157 pub fn delete_to_next_word_boundary(
3158 &mut self,
3159 _: &DeleteToNextWordBoundary,
3160 cx: &mut ViewContext<Self>,
3161 ) {
3162 self.start_transaction(cx);
3163 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3164 let mut selections = self.local_selections::<Point>(cx);
3165 for selection in &mut selections {
3166 if selection.is_empty() {
3167 let head = selection.head().to_display_point(&display_map);
3168 let cursor =
3169 movement::next_word_boundary(&display_map, head).to_point(&display_map);
3170 selection.set_head(cursor);
3171 selection.goal = SelectionGoal::None;
3172 }
3173 }
3174 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3175 self.insert("", cx);
3176 self.end_transaction(cx);
3177 }
3178
3179 pub fn move_to_beginning_of_line(
3180 &mut self,
3181 _: &MoveToBeginningOfLine,
3182 cx: &mut ViewContext<Self>,
3183 ) {
3184 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3185 let mut selections = self.local_selections::<Point>(cx);
3186 for selection in &mut selections {
3187 let head = selection.head().to_display_point(&display_map);
3188 let new_head = movement::line_beginning(&display_map, head, true);
3189 let cursor = new_head.to_point(&display_map);
3190 selection.start = cursor;
3191 selection.end = cursor;
3192 selection.reversed = false;
3193 selection.goal = SelectionGoal::None;
3194 }
3195 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3196 }
3197
3198 pub fn select_to_beginning_of_line(
3199 &mut self,
3200 SelectToBeginningOfLine(stop_at_soft_boundaries): &SelectToBeginningOfLine,
3201 cx: &mut ViewContext<Self>,
3202 ) {
3203 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3204 let mut selections = self.local_selections::<Point>(cx);
3205 for selection in &mut selections {
3206 let head = selection.head().to_display_point(&display_map);
3207 let new_head = movement::line_beginning(&display_map, head, *stop_at_soft_boundaries);
3208 selection.set_head(new_head.to_point(&display_map));
3209 selection.goal = SelectionGoal::None;
3210 }
3211 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3212 }
3213
3214 pub fn delete_to_beginning_of_line(
3215 &mut self,
3216 _: &DeleteToBeginningOfLine,
3217 cx: &mut ViewContext<Self>,
3218 ) {
3219 self.start_transaction(cx);
3220 self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
3221 self.backspace(&Backspace, cx);
3222 self.end_transaction(cx);
3223 }
3224
3225 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
3226 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3227 let mut selections = self.local_selections::<Point>(cx);
3228 {
3229 for selection in &mut selections {
3230 let head = selection.head().to_display_point(&display_map);
3231 let new_head = movement::line_end(&display_map, head, true);
3232 let anchor = new_head.to_point(&display_map);
3233 selection.start = anchor.clone();
3234 selection.end = anchor;
3235 selection.reversed = false;
3236 selection.goal = SelectionGoal::None;
3237 }
3238 }
3239 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3240 }
3241
3242 pub fn select_to_end_of_line(
3243 &mut self,
3244 SelectToEndOfLine(stop_at_soft_boundaries): &SelectToEndOfLine,
3245 cx: &mut ViewContext<Self>,
3246 ) {
3247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3248 let mut selections = self.local_selections::<Point>(cx);
3249 for selection in &mut selections {
3250 let head = selection.head().to_display_point(&display_map);
3251 let new_head = movement::line_end(&display_map, head, *stop_at_soft_boundaries);
3252 selection.set_head(new_head.to_point(&display_map));
3253 selection.goal = SelectionGoal::None;
3254 }
3255 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3256 }
3257
3258 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
3259 self.start_transaction(cx);
3260 self.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3261 self.delete(&Delete, cx);
3262 self.end_transaction(cx);
3263 }
3264
3265 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
3266 self.start_transaction(cx);
3267 self.select_to_end_of_line(&SelectToEndOfLine(false), cx);
3268 self.cut(&Cut, cx);
3269 self.end_transaction(cx);
3270 }
3271
3272 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
3273 if matches!(self.mode, EditorMode::SingleLine) {
3274 cx.propagate_action();
3275 return;
3276 }
3277
3278 let selection = Selection {
3279 id: post_inc(&mut self.next_selection_id),
3280 start: 0,
3281 end: 0,
3282 reversed: false,
3283 goal: SelectionGoal::None,
3284 };
3285 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3286 }
3287
3288 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
3289 let mut selection = self.local_selections::<Point>(cx).last().unwrap().clone();
3290 selection.set_head(Point::zero());
3291 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3292 }
3293
3294 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
3295 if matches!(self.mode, EditorMode::SingleLine) {
3296 cx.propagate_action();
3297 return;
3298 }
3299
3300 let cursor = self.buffer.read(cx).read(cx).len();
3301 let selection = Selection {
3302 id: post_inc(&mut self.next_selection_id),
3303 start: cursor,
3304 end: cursor,
3305 reversed: false,
3306 goal: SelectionGoal::None,
3307 };
3308 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3309 }
3310
3311 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
3312 self.nav_history = nav_history;
3313 }
3314
3315 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
3316 self.nav_history.as_ref()
3317 }
3318
3319 fn push_to_nav_history(
3320 &self,
3321 position: Anchor,
3322 new_position: Option<Point>,
3323 cx: &mut ViewContext<Self>,
3324 ) {
3325 if let Some(nav_history) = &self.nav_history {
3326 let buffer = self.buffer.read(cx).read(cx);
3327 let offset = position.to_offset(&buffer);
3328 let point = position.to_point(&buffer);
3329 drop(buffer);
3330
3331 if let Some(new_position) = new_position {
3332 let row_delta = (new_position.row as i64 - point.row as i64).abs();
3333 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
3334 return;
3335 }
3336 }
3337
3338 nav_history.push(Some(NavigationData {
3339 anchor: position,
3340 offset,
3341 }));
3342 }
3343 }
3344
3345 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
3346 let mut selection = self.local_selections::<usize>(cx).first().unwrap().clone();
3347 selection.set_head(self.buffer.read(cx).read(cx).len());
3348 self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
3349 }
3350
3351 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
3352 let selection = Selection {
3353 id: post_inc(&mut self.next_selection_id),
3354 start: 0,
3355 end: self.buffer.read(cx).read(cx).len(),
3356 reversed: false,
3357 goal: SelectionGoal::None,
3358 };
3359 self.update_selections(vec![selection], None, cx);
3360 }
3361
3362 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
3363 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3364 let mut selections = self.local_selections::<Point>(cx);
3365 let max_point = display_map.buffer_snapshot.max_point();
3366 for selection in &mut selections {
3367 let rows = selection.spanned_rows(true, &display_map);
3368 selection.start = Point::new(rows.start, 0);
3369 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
3370 selection.reversed = false;
3371 }
3372 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3373 }
3374
3375 pub fn split_selection_into_lines(
3376 &mut self,
3377 _: &SplitSelectionIntoLines,
3378 cx: &mut ViewContext<Self>,
3379 ) {
3380 let mut to_unfold = Vec::new();
3381 let mut new_selections = Vec::new();
3382 {
3383 let selections = self.local_selections::<Point>(cx);
3384 let buffer = self.buffer.read(cx).read(cx);
3385 for selection in selections {
3386 for row in selection.start.row..selection.end.row {
3387 let cursor = Point::new(row, buffer.line_len(row));
3388 new_selections.push(Selection {
3389 id: post_inc(&mut self.next_selection_id),
3390 start: cursor,
3391 end: cursor,
3392 reversed: false,
3393 goal: SelectionGoal::None,
3394 });
3395 }
3396 new_selections.push(Selection {
3397 id: selection.id,
3398 start: selection.end,
3399 end: selection.end,
3400 reversed: false,
3401 goal: SelectionGoal::None,
3402 });
3403 to_unfold.push(selection.start..selection.end);
3404 }
3405 }
3406 self.unfold_ranges(to_unfold, cx);
3407 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3408 }
3409
3410 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
3411 self.add_selection(true, cx);
3412 }
3413
3414 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
3415 self.add_selection(false, cx);
3416 }
3417
3418 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
3419 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3420 let mut selections = self.local_selections::<Point>(cx);
3421 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
3422 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
3423 let range = oldest_selection.display_range(&display_map).sorted();
3424 let columns = cmp::min(range.start.column(), range.end.column())
3425 ..cmp::max(range.start.column(), range.end.column());
3426
3427 selections.clear();
3428 let mut stack = Vec::new();
3429 for row in range.start.row()..=range.end.row() {
3430 if let Some(selection) = self.build_columnar_selection(
3431 &display_map,
3432 row,
3433 &columns,
3434 oldest_selection.reversed,
3435 ) {
3436 stack.push(selection.id);
3437 selections.push(selection);
3438 }
3439 }
3440
3441 if above {
3442 stack.reverse();
3443 }
3444
3445 AddSelectionsState { above, stack }
3446 });
3447
3448 let last_added_selection = *state.stack.last().unwrap();
3449 let mut new_selections = Vec::new();
3450 if above == state.above {
3451 let end_row = if above {
3452 0
3453 } else {
3454 display_map.max_point().row()
3455 };
3456
3457 'outer: for selection in selections {
3458 if selection.id == last_added_selection {
3459 let range = selection.display_range(&display_map).sorted();
3460 debug_assert_eq!(range.start.row(), range.end.row());
3461 let mut row = range.start.row();
3462 let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
3463 {
3464 start..end
3465 } else {
3466 cmp::min(range.start.column(), range.end.column())
3467 ..cmp::max(range.start.column(), range.end.column())
3468 };
3469
3470 while row != end_row {
3471 if above {
3472 row -= 1;
3473 } else {
3474 row += 1;
3475 }
3476
3477 if let Some(new_selection) = self.build_columnar_selection(
3478 &display_map,
3479 row,
3480 &columns,
3481 selection.reversed,
3482 ) {
3483 state.stack.push(new_selection.id);
3484 if above {
3485 new_selections.push(new_selection);
3486 new_selections.push(selection);
3487 } else {
3488 new_selections.push(selection);
3489 new_selections.push(new_selection);
3490 }
3491
3492 continue 'outer;
3493 }
3494 }
3495 }
3496
3497 new_selections.push(selection);
3498 }
3499 } else {
3500 new_selections = selections;
3501 new_selections.retain(|s| s.id != last_added_selection);
3502 state.stack.pop();
3503 }
3504
3505 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3506 if state.stack.len() > 1 {
3507 self.add_selections_state = Some(state);
3508 }
3509 }
3510
3511 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
3512 let replace_newest = action.0;
3513 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3514 let buffer = &display_map.buffer_snapshot;
3515 let mut selections = self.local_selections::<usize>(cx);
3516 if let Some(mut select_next_state) = self.select_next_state.take() {
3517 let query = &select_next_state.query;
3518 if !select_next_state.done {
3519 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
3520 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
3521 let mut next_selected_range = None;
3522
3523 let bytes_after_last_selection =
3524 buffer.bytes_in_range(last_selection.end..buffer.len());
3525 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
3526 let query_matches = query
3527 .stream_find_iter(bytes_after_last_selection)
3528 .map(|result| (last_selection.end, result))
3529 .chain(
3530 query
3531 .stream_find_iter(bytes_before_first_selection)
3532 .map(|result| (0, result)),
3533 );
3534 for (start_offset, query_match) in query_matches {
3535 let query_match = query_match.unwrap(); // can only fail due to I/O
3536 let offset_range =
3537 start_offset + query_match.start()..start_offset + query_match.end();
3538 let display_range = offset_range.start.to_display_point(&display_map)
3539 ..offset_range.end.to_display_point(&display_map);
3540
3541 if !select_next_state.wordwise
3542 || (!movement::is_inside_word(&display_map, display_range.start)
3543 && !movement::is_inside_word(&display_map, display_range.end))
3544 {
3545 next_selected_range = Some(offset_range);
3546 break;
3547 }
3548 }
3549
3550 if let Some(next_selected_range) = next_selected_range {
3551 if replace_newest {
3552 if let Some(newest_id) =
3553 selections.iter().max_by_key(|s| s.id).map(|s| s.id)
3554 {
3555 selections.retain(|s| s.id != newest_id);
3556 }
3557 }
3558 selections.push(Selection {
3559 id: post_inc(&mut self.next_selection_id),
3560 start: next_selected_range.start,
3561 end: next_selected_range.end,
3562 reversed: false,
3563 goal: SelectionGoal::None,
3564 });
3565 self.update_selections(selections, Some(Autoscroll::Newest), cx);
3566 } else {
3567 select_next_state.done = true;
3568 }
3569 }
3570
3571 self.select_next_state = Some(select_next_state);
3572 } else if selections.len() == 1 {
3573 let selection = selections.last_mut().unwrap();
3574 if selection.start == selection.end {
3575 let word_range = movement::surrounding_word(
3576 &display_map,
3577 selection.start.to_display_point(&display_map),
3578 );
3579 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
3580 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
3581 selection.goal = SelectionGoal::None;
3582 selection.reversed = false;
3583
3584 let query = buffer
3585 .text_for_range(selection.start..selection.end)
3586 .collect::<String>();
3587 let select_state = SelectNextState {
3588 query: AhoCorasick::new_auto_configured(&[query]),
3589 wordwise: true,
3590 done: false,
3591 };
3592 self.update_selections(selections, Some(Autoscroll::Newest), cx);
3593 self.select_next_state = Some(select_state);
3594 } else {
3595 let query = buffer
3596 .text_for_range(selection.start..selection.end)
3597 .collect::<String>();
3598 self.select_next_state = Some(SelectNextState {
3599 query: AhoCorasick::new_auto_configured(&[query]),
3600 wordwise: false,
3601 done: false,
3602 });
3603 self.select_next(action, cx);
3604 }
3605 }
3606 }
3607
3608 pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
3609 // Get the line comment prefix. Split its trailing whitespace into a separate string,
3610 // as that portion won't be used for detecting if a line is a comment.
3611 let full_comment_prefix =
3612 if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
3613 prefix.to_string()
3614 } else {
3615 return;
3616 };
3617 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
3618 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
3619
3620 self.start_transaction(cx);
3621 let mut selections = self.local_selections::<Point>(cx);
3622 let mut all_selection_lines_are_comments = true;
3623 let mut edit_ranges = Vec::new();
3624 let mut last_toggled_row = None;
3625 self.buffer.update(cx, |buffer, cx| {
3626 for selection in &mut selections {
3627 edit_ranges.clear();
3628 let snapshot = buffer.snapshot(cx);
3629
3630 let end_row =
3631 if selection.end.row > selection.start.row && selection.end.column == 0 {
3632 selection.end.row
3633 } else {
3634 selection.end.row + 1
3635 };
3636
3637 for row in selection.start.row..end_row {
3638 // If multiple selections contain a given row, avoid processing that
3639 // row more than once.
3640 if last_toggled_row == Some(row) {
3641 continue;
3642 } else {
3643 last_toggled_row = Some(row);
3644 }
3645
3646 if snapshot.is_line_blank(row) {
3647 continue;
3648 }
3649
3650 let start = Point::new(row, snapshot.indent_column_for_line(row));
3651 let mut line_bytes = snapshot
3652 .bytes_in_range(start..snapshot.max_point())
3653 .flatten()
3654 .copied();
3655
3656 // If this line currently begins with the line comment prefix, then record
3657 // the range containing the prefix.
3658 if all_selection_lines_are_comments
3659 && line_bytes
3660 .by_ref()
3661 .take(comment_prefix.len())
3662 .eq(comment_prefix.bytes())
3663 {
3664 // Include any whitespace that matches the comment prefix.
3665 let matching_whitespace_len = line_bytes
3666 .zip(comment_prefix_whitespace.bytes())
3667 .take_while(|(a, b)| a == b)
3668 .count() as u32;
3669 let end = Point::new(
3670 row,
3671 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
3672 );
3673 edit_ranges.push(start..end);
3674 }
3675 // If this line does not begin with the line comment prefix, then record
3676 // the position where the prefix should be inserted.
3677 else {
3678 all_selection_lines_are_comments = false;
3679 edit_ranges.push(start..start);
3680 }
3681 }
3682
3683 if !edit_ranges.is_empty() {
3684 if all_selection_lines_are_comments {
3685 buffer.edit(edit_ranges.iter().cloned(), "", cx);
3686 } else {
3687 let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
3688 let edit_ranges = edit_ranges.iter().map(|range| {
3689 let position = Point::new(range.start.row, min_column);
3690 position..position
3691 });
3692 buffer.edit(edit_ranges, &full_comment_prefix, cx);
3693 }
3694 }
3695 }
3696 });
3697
3698 self.update_selections(
3699 self.local_selections::<usize>(cx),
3700 Some(Autoscroll::Fit),
3701 cx,
3702 );
3703 self.end_transaction(cx);
3704 }
3705
3706 pub fn select_larger_syntax_node(
3707 &mut self,
3708 _: &SelectLargerSyntaxNode,
3709 cx: &mut ViewContext<Self>,
3710 ) {
3711 let old_selections = self.local_selections::<usize>(cx).into_boxed_slice();
3712 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3713 let buffer = self.buffer.read(cx).snapshot(cx);
3714
3715 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
3716 let mut selected_larger_node = false;
3717 let new_selections = old_selections
3718 .iter()
3719 .map(|selection| {
3720 let old_range = selection.start..selection.end;
3721 let mut new_range = old_range.clone();
3722 while let Some(containing_range) =
3723 buffer.range_for_syntax_ancestor(new_range.clone())
3724 {
3725 new_range = containing_range;
3726 if !display_map.intersects_fold(new_range.start)
3727 && !display_map.intersects_fold(new_range.end)
3728 {
3729 break;
3730 }
3731 }
3732
3733 selected_larger_node |= new_range != old_range;
3734 Selection {
3735 id: selection.id,
3736 start: new_range.start,
3737 end: new_range.end,
3738 goal: SelectionGoal::None,
3739 reversed: selection.reversed,
3740 }
3741 })
3742 .collect::<Vec<_>>();
3743
3744 if selected_larger_node {
3745 stack.push(old_selections);
3746 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
3747 }
3748 self.select_larger_syntax_node_stack = stack;
3749 }
3750
3751 pub fn select_smaller_syntax_node(
3752 &mut self,
3753 _: &SelectSmallerSyntaxNode,
3754 cx: &mut ViewContext<Self>,
3755 ) {
3756 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
3757 if let Some(selections) = stack.pop() {
3758 self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
3759 }
3760 self.select_larger_syntax_node_stack = stack;
3761 }
3762
3763 pub fn move_to_enclosing_bracket(
3764 &mut self,
3765 _: &MoveToEnclosingBracket,
3766 cx: &mut ViewContext<Self>,
3767 ) {
3768 let mut selections = self.local_selections::<usize>(cx);
3769 let buffer = self.buffer.read(cx).snapshot(cx);
3770 for selection in &mut selections {
3771 if let Some((open_range, close_range)) =
3772 buffer.enclosing_bracket_ranges(selection.start..selection.end)
3773 {
3774 let close_range = close_range.to_inclusive();
3775 let destination = if close_range.contains(&selection.start)
3776 && close_range.contains(&selection.end)
3777 {
3778 open_range.end
3779 } else {
3780 *close_range.start()
3781 };
3782 selection.start = destination;
3783 selection.end = destination;
3784 }
3785 }
3786
3787 self.update_selections(selections, Some(Autoscroll::Fit), cx);
3788 }
3789
3790 pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
3791 let buffer = self.buffer.read(cx).snapshot(cx);
3792 let selection = self.newest_selection::<usize>(&buffer);
3793 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
3794 active_diagnostics
3795 .primary_range
3796 .to_offset(&buffer)
3797 .to_inclusive()
3798 });
3799 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
3800 if active_primary_range.contains(&selection.head()) {
3801 *active_primary_range.end()
3802 } else {
3803 selection.head()
3804 }
3805 } else {
3806 selection.head()
3807 };
3808
3809 loop {
3810 let next_group = buffer
3811 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
3812 .find_map(|entry| {
3813 if entry.diagnostic.is_primary
3814 && !entry.range.is_empty()
3815 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
3816 {
3817 Some((entry.range, entry.diagnostic.group_id))
3818 } else {
3819 None
3820 }
3821 });
3822
3823 if let Some((primary_range, group_id)) = next_group {
3824 self.activate_diagnostics(group_id, cx);
3825 self.update_selections(
3826 vec![Selection {
3827 id: selection.id,
3828 start: primary_range.start,
3829 end: primary_range.start,
3830 reversed: false,
3831 goal: SelectionGoal::None,
3832 }],
3833 Some(Autoscroll::Center),
3834 cx,
3835 );
3836 break;
3837 } else if search_start == 0 {
3838 break;
3839 } else {
3840 // Cycle around to the start of the buffer, potentially moving back to the start of
3841 // the currently active diagnostic.
3842 search_start = 0;
3843 active_primary_range.take();
3844 }
3845 }
3846 }
3847
3848 pub fn go_to_definition(
3849 workspace: &mut Workspace,
3850 _: &GoToDefinition,
3851 cx: &mut ViewContext<Workspace>,
3852 ) {
3853 let active_item = workspace.active_item(cx);
3854 let editor_handle = if let Some(editor) = active_item
3855 .as_ref()
3856 .and_then(|item| item.act_as::<Self>(cx))
3857 {
3858 editor
3859 } else {
3860 return;
3861 };
3862
3863 let editor = editor_handle.read(cx);
3864 let buffer = editor.buffer.read(cx);
3865 let head = editor.newest_selection::<usize>(&buffer.read(cx)).head();
3866 let (buffer, head) = editor.buffer.read(cx).text_anchor_for_position(head, cx);
3867 let definitions = workspace
3868 .project()
3869 .update(cx, |project, cx| project.definition(&buffer, head, cx));
3870 cx.spawn(|workspace, mut cx| async move {
3871 let definitions = definitions.await?;
3872 workspace.update(&mut cx, |workspace, cx| {
3873 for definition in definitions {
3874 let range = definition
3875 .target_range
3876 .to_offset(definition.target_buffer.read(cx));
3877 let target_editor_handle = workspace
3878 .open_item(BufferItemHandle(definition.target_buffer), cx)
3879 .downcast::<Self>()
3880 .unwrap();
3881
3882 target_editor_handle.update(cx, |target_editor, cx| {
3883 // When selecting a definition in a different buffer, disable the nav history
3884 // to avoid creating a history entry at the previous cursor location.
3885 let disabled_history = if editor_handle == target_editor_handle {
3886 None
3887 } else {
3888 target_editor.nav_history.take()
3889 };
3890 target_editor.select_ranges([range], Some(Autoscroll::Center), cx);
3891 if disabled_history.is_some() {
3892 target_editor.nav_history = disabled_history;
3893 }
3894 });
3895 }
3896 });
3897
3898 Ok::<(), anyhow::Error>(())
3899 })
3900 .detach_and_log_err(cx);
3901 }
3902
3903 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
3904 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
3905 let buffer = self.buffer.read(cx).snapshot(cx);
3906 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
3907 let is_valid = buffer
3908 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
3909 .any(|entry| {
3910 entry.diagnostic.is_primary
3911 && !entry.range.is_empty()
3912 && entry.range.start == primary_range_start
3913 && entry.diagnostic.message == active_diagnostics.primary_message
3914 });
3915
3916 if is_valid != active_diagnostics.is_valid {
3917 active_diagnostics.is_valid = is_valid;
3918 let mut new_styles = HashMap::default();
3919 for (block_id, diagnostic) in &active_diagnostics.blocks {
3920 new_styles.insert(
3921 *block_id,
3922 diagnostic_block_renderer(
3923 diagnostic.clone(),
3924 is_valid,
3925 self.build_settings.clone(),
3926 ),
3927 );
3928 }
3929 self.display_map
3930 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
3931 }
3932 }
3933 }
3934
3935 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
3936 self.dismiss_diagnostics(cx);
3937 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
3938 let buffer = self.buffer.read(cx).snapshot(cx);
3939
3940 let mut primary_range = None;
3941 let mut primary_message = None;
3942 let mut group_end = Point::zero();
3943 let diagnostic_group = buffer
3944 .diagnostic_group::<Point>(group_id)
3945 .map(|entry| {
3946 if entry.range.end > group_end {
3947 group_end = entry.range.end;
3948 }
3949 if entry.diagnostic.is_primary {
3950 primary_range = Some(entry.range.clone());
3951 primary_message = Some(entry.diagnostic.message.clone());
3952 }
3953 entry
3954 })
3955 .collect::<Vec<_>>();
3956 let primary_range = primary_range.unwrap();
3957 let primary_message = primary_message.unwrap();
3958 let primary_range =
3959 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
3960
3961 let blocks = display_map
3962 .insert_blocks(
3963 diagnostic_group.iter().map(|entry| {
3964 let build_settings = self.build_settings.clone();
3965 let diagnostic = entry.diagnostic.clone();
3966 let message_height = diagnostic.message.lines().count() as u8;
3967
3968 BlockProperties {
3969 position: buffer.anchor_after(entry.range.start),
3970 height: message_height,
3971 render: diagnostic_block_renderer(diagnostic, true, build_settings),
3972 disposition: BlockDisposition::Below,
3973 }
3974 }),
3975 cx,
3976 )
3977 .into_iter()
3978 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
3979 .collect();
3980
3981 Some(ActiveDiagnosticGroup {
3982 primary_range,
3983 primary_message,
3984 blocks,
3985 is_valid: true,
3986 })
3987 });
3988 }
3989
3990 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
3991 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
3992 self.display_map.update(cx, |display_map, cx| {
3993 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
3994 });
3995 cx.notify();
3996 }
3997 }
3998
3999 fn build_columnar_selection(
4000 &mut self,
4001 display_map: &DisplaySnapshot,
4002 row: u32,
4003 columns: &Range<u32>,
4004 reversed: bool,
4005 ) -> Option<Selection<Point>> {
4006 let is_empty = columns.start == columns.end;
4007 let line_len = display_map.line_len(row);
4008 if columns.start < line_len || (is_empty && columns.start == line_len) {
4009 let start = DisplayPoint::new(row, columns.start);
4010 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
4011 Some(Selection {
4012 id: post_inc(&mut self.next_selection_id),
4013 start: start.to_point(display_map),
4014 end: end.to_point(display_map),
4015 reversed,
4016 goal: SelectionGoal::ColumnRange {
4017 start: columns.start,
4018 end: columns.end,
4019 },
4020 })
4021 } else {
4022 None
4023 }
4024 }
4025
4026 pub fn local_selections_in_range(
4027 &self,
4028 range: Range<Anchor>,
4029 display_map: &DisplaySnapshot,
4030 ) -> Vec<Selection<Point>> {
4031 let buffer = &display_map.buffer_snapshot;
4032
4033 let start_ix = match self
4034 .selections
4035 .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer).unwrap())
4036 {
4037 Ok(ix) | Err(ix) => ix,
4038 };
4039 let end_ix = match self
4040 .selections
4041 .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer).unwrap())
4042 {
4043 Ok(ix) => ix + 1,
4044 Err(ix) => ix,
4045 };
4046
4047 fn point_selection(
4048 selection: &Selection<Anchor>,
4049 buffer: &MultiBufferSnapshot,
4050 ) -> Selection<Point> {
4051 let start = selection.start.to_point(&buffer);
4052 let end = selection.end.to_point(&buffer);
4053 Selection {
4054 id: selection.id,
4055 start,
4056 end,
4057 reversed: selection.reversed,
4058 goal: selection.goal,
4059 }
4060 }
4061
4062 self.selections[start_ix..end_ix]
4063 .iter()
4064 .chain(
4065 self.pending_selection
4066 .as_ref()
4067 .map(|pending| &pending.selection),
4068 )
4069 .map(|s| point_selection(s, &buffer))
4070 .collect()
4071 }
4072
4073 pub fn local_selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
4074 where
4075 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
4076 {
4077 let buffer = self.buffer.read(cx).snapshot(cx);
4078 let mut selections = self
4079 .resolve_selections::<D, _>(self.selections.iter(), &buffer)
4080 .peekable();
4081
4082 let mut pending_selection = self.pending_selection::<D>(&buffer);
4083
4084 iter::from_fn(move || {
4085 if let Some(pending) = pending_selection.as_mut() {
4086 while let Some(next_selection) = selections.peek() {
4087 if pending.start <= next_selection.end && pending.end >= next_selection.start {
4088 let next_selection = selections.next().unwrap();
4089 if next_selection.start < pending.start {
4090 pending.start = next_selection.start;
4091 }
4092 if next_selection.end > pending.end {
4093 pending.end = next_selection.end;
4094 }
4095 } else if next_selection.end < pending.start {
4096 return selections.next();
4097 } else {
4098 break;
4099 }
4100 }
4101
4102 pending_selection.take()
4103 } else {
4104 selections.next()
4105 }
4106 })
4107 .collect()
4108 }
4109
4110 fn resolve_selections<'a, D, I>(
4111 &self,
4112 selections: I,
4113 snapshot: &MultiBufferSnapshot,
4114 ) -> impl 'a + Iterator<Item = Selection<D>>
4115 where
4116 D: TextDimension + Ord + Sub<D, Output = D>,
4117 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
4118 {
4119 let (to_summarize, selections) = selections.into_iter().tee();
4120 let mut summaries = snapshot
4121 .summaries_for_anchors::<D, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
4122 .into_iter();
4123 selections.map(move |s| Selection {
4124 id: s.id,
4125 start: summaries.next().unwrap(),
4126 end: summaries.next().unwrap(),
4127 reversed: s.reversed,
4128 goal: s.goal,
4129 })
4130 }
4131
4132 fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4133 &self,
4134 snapshot: &MultiBufferSnapshot,
4135 ) -> Option<Selection<D>> {
4136 self.pending_selection
4137 .as_ref()
4138 .map(|pending| self.resolve_selection(&pending.selection, &snapshot))
4139 }
4140
4141 fn resolve_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4142 &self,
4143 selection: &Selection<Anchor>,
4144 buffer: &MultiBufferSnapshot,
4145 ) -> Selection<D> {
4146 Selection {
4147 id: selection.id,
4148 start: selection.start.summary::<D>(&buffer),
4149 end: selection.end.summary::<D>(&buffer),
4150 reversed: selection.reversed,
4151 goal: selection.goal,
4152 }
4153 }
4154
4155 fn selection_count<'a>(&self) -> usize {
4156 let mut count = self.selections.len();
4157 if self.pending_selection.is_some() {
4158 count += 1;
4159 }
4160 count
4161 }
4162
4163 pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4164 &self,
4165 snapshot: &MultiBufferSnapshot,
4166 ) -> Selection<D> {
4167 self.selections
4168 .iter()
4169 .min_by_key(|s| s.id)
4170 .map(|selection| self.resolve_selection(selection, snapshot))
4171 .or_else(|| self.pending_selection(snapshot))
4172 .unwrap()
4173 }
4174
4175 pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
4176 &self,
4177 snapshot: &MultiBufferSnapshot,
4178 ) -> Selection<D> {
4179 self.resolve_selection(self.newest_anchor_selection().unwrap(), snapshot)
4180 }
4181
4182 pub fn newest_anchor_selection(&self) -> Option<&Selection<Anchor>> {
4183 self.pending_selection
4184 .as_ref()
4185 .map(|s| &s.selection)
4186 .or_else(|| self.selections.iter().max_by_key(|s| s.id))
4187 }
4188
4189 pub fn update_selections<T>(
4190 &mut self,
4191 mut selections: Vec<Selection<T>>,
4192 autoscroll: Option<Autoscroll>,
4193 cx: &mut ViewContext<Self>,
4194 ) where
4195 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
4196 {
4197 let buffer = self.buffer.read(cx).snapshot(cx);
4198 selections.sort_unstable_by_key(|s| s.start);
4199
4200 // Merge overlapping selections.
4201 let mut i = 1;
4202 while i < selections.len() {
4203 if selections[i - 1].end >= selections[i].start {
4204 let removed = selections.remove(i);
4205 if removed.start < selections[i - 1].start {
4206 selections[i - 1].start = removed.start;
4207 }
4208 if removed.end > selections[i - 1].end {
4209 selections[i - 1].end = removed.end;
4210 }
4211 } else {
4212 i += 1;
4213 }
4214 }
4215
4216 if let Some(autoscroll) = autoscroll {
4217 self.request_autoscroll(autoscroll, cx);
4218 }
4219
4220 self.set_selections(
4221 Arc::from_iter(selections.into_iter().map(|selection| {
4222 let end_bias = if selection.end > selection.start {
4223 Bias::Left
4224 } else {
4225 Bias::Right
4226 };
4227 Selection {
4228 id: selection.id,
4229 start: buffer.anchor_after(selection.start),
4230 end: buffer.anchor_at(selection.end, end_bias),
4231 reversed: selection.reversed,
4232 goal: selection.goal,
4233 }
4234 })),
4235 cx,
4236 );
4237 }
4238
4239 /// Compute new ranges for any selections that were located in excerpts that have
4240 /// since been removed.
4241 ///
4242 /// Returns a `HashMap` indicating which selections whose former head position
4243 /// was no longer present. The keys of the map are selection ids. The values are
4244 /// the id of the new excerpt where the head of the selection has been moved.
4245 pub fn refresh_selections(&mut self, cx: &mut ViewContext<Self>) -> HashMap<usize, ExcerptId> {
4246 let snapshot = self.buffer.read(cx).read(cx);
4247 let anchors_with_status = snapshot.refresh_anchors(
4248 self.selections
4249 .iter()
4250 .flat_map(|selection| [&selection.start, &selection.end]),
4251 );
4252 let offsets =
4253 snapshot.summaries_for_anchors::<usize, _>(anchors_with_status.iter().map(|a| &a.1));
4254 let offsets = offsets.chunks(2);
4255 let statuses = anchors_with_status
4256 .chunks(2)
4257 .map(|a| (a[0].0 / 2, a[0].2, a[1].2));
4258
4259 let mut selections_with_lost_position = HashMap::default();
4260 let new_selections = offsets
4261 .zip(statuses)
4262 .map(|(offsets, (selection_ix, kept_start, kept_end))| {
4263 let selection = &self.selections[selection_ix];
4264 let kept_head = if selection.reversed {
4265 kept_start
4266 } else {
4267 kept_end
4268 };
4269 if !kept_head {
4270 selections_with_lost_position
4271 .insert(selection.id, selection.head().excerpt_id.clone());
4272 }
4273
4274 Selection {
4275 id: selection.id,
4276 start: offsets[0],
4277 end: offsets[1],
4278 reversed: selection.reversed,
4279 goal: selection.goal,
4280 }
4281 })
4282 .collect();
4283 drop(snapshot);
4284 self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
4285 selections_with_lost_position
4286 }
4287
4288 fn set_selections(&mut self, selections: Arc<[Selection<Anchor>]>, cx: &mut ViewContext<Self>) {
4289 let old_cursor_position = self.newest_anchor_selection().map(|s| s.head());
4290 self.selections = selections;
4291 if self.focused {
4292 self.buffer.update(cx, |buffer, cx| {
4293 buffer.set_active_selections(&self.selections, cx)
4294 });
4295 }
4296
4297 let buffer = self.buffer.read(cx).snapshot(cx);
4298 self.pending_selection = None;
4299 self.add_selections_state = None;
4300 self.select_next_state = None;
4301 self.select_larger_syntax_node_stack.clear();
4302 self.autoclose_stack.invalidate(&self.selections, &buffer);
4303 self.snippet_stack.invalidate(&self.selections, &buffer);
4304
4305 let new_cursor_position = self
4306 .selections
4307 .iter()
4308 .max_by_key(|s| s.id)
4309 .map(|s| s.head());
4310 if let Some(old_cursor_position) = old_cursor_position {
4311 if let Some(new_cursor_position) = new_cursor_position.as_ref() {
4312 self.push_to_nav_history(
4313 old_cursor_position,
4314 Some(new_cursor_position.to_point(&buffer)),
4315 cx,
4316 );
4317 }
4318 }
4319
4320 let completion_menu = match self.context_menu.as_mut() {
4321 Some(ContextMenu::Completions(menu)) => Some(menu),
4322 _ => {
4323 self.context_menu.take();
4324 None
4325 }
4326 };
4327
4328 if let Some((completion_menu, cursor_position)) = completion_menu.zip(new_cursor_position) {
4329 let cursor_position = cursor_position.to_offset(&buffer);
4330 let (word_range, kind) =
4331 buffer.surrounding_word(completion_menu.initial_position.clone());
4332 if kind == Some(CharKind::Word) && word_range.to_inclusive().contains(&cursor_position)
4333 {
4334 let query = Self::completion_query(&buffer, cursor_position);
4335 cx.background()
4336 .block(completion_menu.filter(query.as_deref(), cx.background().clone()));
4337 self.show_completions(&ShowCompletions, cx);
4338 } else {
4339 self.hide_context_menu(cx);
4340 }
4341 }
4342
4343 self.pause_cursor_blinking(cx);
4344 cx.emit(Event::SelectionsChanged);
4345 }
4346
4347 pub fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
4348 self.autoscroll_request = Some(autoscroll);
4349 cx.notify();
4350 }
4351
4352 fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
4353 self.start_transaction_at(Instant::now(), cx);
4354 }
4355
4356 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
4357 self.end_selection(cx);
4358 if let Some(tx_id) = self
4359 .buffer
4360 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
4361 {
4362 self.selection_history
4363 .insert(tx_id, (self.selections.clone(), None));
4364 }
4365 }
4366
4367 fn end_transaction(&mut self, cx: &mut ViewContext<Self>) {
4368 self.end_transaction_at(Instant::now(), cx);
4369 }
4370
4371 fn end_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
4372 if let Some(tx_id) = self
4373 .buffer
4374 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
4375 {
4376 if let Some((_, end_selections)) = self.selection_history.get_mut(&tx_id) {
4377 *end_selections = Some(self.selections.clone());
4378 } else {
4379 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
4380 }
4381 }
4382 }
4383
4384 pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
4385 log::info!("Editor::page_up");
4386 }
4387
4388 pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
4389 log::info!("Editor::page_down");
4390 }
4391
4392 pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
4393 let mut fold_ranges = Vec::new();
4394
4395 let selections = self.local_selections::<Point>(cx);
4396 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4397 for selection in selections {
4398 let range = selection.display_range(&display_map).sorted();
4399 let buffer_start_row = range.start.to_point(&display_map).row;
4400
4401 for row in (0..=range.end.row()).rev() {
4402 if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
4403 let fold_range = self.foldable_range_for_line(&display_map, row);
4404 if fold_range.end.row >= buffer_start_row {
4405 fold_ranges.push(fold_range);
4406 if row <= range.start.row() {
4407 break;
4408 }
4409 }
4410 }
4411 }
4412 }
4413
4414 self.fold_ranges(fold_ranges, cx);
4415 }
4416
4417 pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
4418 let selections = self.local_selections::<Point>(cx);
4419 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4420 let buffer = &display_map.buffer_snapshot;
4421 let ranges = selections
4422 .iter()
4423 .map(|s| {
4424 let range = s.display_range(&display_map).sorted();
4425 let mut start = range.start.to_point(&display_map);
4426 let mut end = range.end.to_point(&display_map);
4427 start.column = 0;
4428 end.column = buffer.line_len(end.row);
4429 start..end
4430 })
4431 .collect::<Vec<_>>();
4432 self.unfold_ranges(ranges, cx);
4433 }
4434
4435 fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
4436 let max_point = display_map.max_point();
4437 if display_row >= max_point.row() {
4438 false
4439 } else {
4440 let (start_indent, is_blank) = display_map.line_indent(display_row);
4441 if is_blank {
4442 false
4443 } else {
4444 for display_row in display_row + 1..=max_point.row() {
4445 let (indent, is_blank) = display_map.line_indent(display_row);
4446 if !is_blank {
4447 return indent > start_indent;
4448 }
4449 }
4450 false
4451 }
4452 }
4453 }
4454
4455 fn foldable_range_for_line(
4456 &self,
4457 display_map: &DisplaySnapshot,
4458 start_row: u32,
4459 ) -> Range<Point> {
4460 let max_point = display_map.max_point();
4461
4462 let (start_indent, _) = display_map.line_indent(start_row);
4463 let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
4464 let mut end = None;
4465 for row in start_row + 1..=max_point.row() {
4466 let (indent, is_blank) = display_map.line_indent(row);
4467 if !is_blank && indent <= start_indent {
4468 end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
4469 break;
4470 }
4471 }
4472
4473 let end = end.unwrap_or(max_point);
4474 return start.to_point(display_map)..end.to_point(display_map);
4475 }
4476
4477 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
4478 let selections = self.local_selections::<Point>(cx);
4479 let ranges = selections.into_iter().map(|s| s.start..s.end);
4480 self.fold_ranges(ranges, cx);
4481 }
4482
4483 fn fold_ranges<T: ToOffset>(
4484 &mut self,
4485 ranges: impl IntoIterator<Item = Range<T>>,
4486 cx: &mut ViewContext<Self>,
4487 ) {
4488 let mut ranges = ranges.into_iter().peekable();
4489 if ranges.peek().is_some() {
4490 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
4491 self.request_autoscroll(Autoscroll::Fit, cx);
4492 cx.notify();
4493 }
4494 }
4495
4496 fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
4497 if !ranges.is_empty() {
4498 self.display_map
4499 .update(cx, |map, cx| map.unfold(ranges, cx));
4500 self.request_autoscroll(Autoscroll::Fit, cx);
4501 cx.notify();
4502 }
4503 }
4504
4505 pub fn insert_blocks(
4506 &mut self,
4507 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
4508 cx: &mut ViewContext<Self>,
4509 ) -> Vec<BlockId> {
4510 let blocks = self
4511 .display_map
4512 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
4513 self.request_autoscroll(Autoscroll::Fit, cx);
4514 blocks
4515 }
4516
4517 pub fn replace_blocks(
4518 &mut self,
4519 blocks: HashMap<BlockId, RenderBlock>,
4520 cx: &mut ViewContext<Self>,
4521 ) {
4522 self.display_map
4523 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
4524 self.request_autoscroll(Autoscroll::Fit, cx);
4525 }
4526
4527 pub fn remove_blocks(&mut self, block_ids: HashSet<BlockId>, cx: &mut ViewContext<Self>) {
4528 self.display_map.update(cx, |display_map, cx| {
4529 display_map.remove_blocks(block_ids, cx)
4530 });
4531 }
4532
4533 pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
4534 self.display_map
4535 .update(cx, |map, cx| map.snapshot(cx))
4536 .longest_row()
4537 }
4538
4539 pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
4540 self.display_map
4541 .update(cx, |map, cx| map.snapshot(cx))
4542 .max_point()
4543 }
4544
4545 pub fn text(&self, cx: &AppContext) -> String {
4546 self.buffer.read(cx).read(cx).text()
4547 }
4548
4549 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
4550 self.display_map
4551 .update(cx, |map, cx| map.snapshot(cx))
4552 .text()
4553 }
4554
4555 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
4556 self.display_map
4557 .update(cx, |map, cx| map.set_wrap_width(width, cx))
4558 }
4559
4560 pub fn set_highlighted_rows(&mut self, rows: Option<Range<u32>>) {
4561 self.highlighted_rows = rows;
4562 }
4563
4564 pub fn highlighted_rows(&self) -> Option<Range<u32>> {
4565 self.highlighted_rows.clone()
4566 }
4567
4568 pub fn highlight_ranges<T: 'static>(
4569 &mut self,
4570 ranges: Vec<Range<Anchor>>,
4571 color: Color,
4572 cx: &mut ViewContext<Self>,
4573 ) {
4574 self.highlighted_ranges
4575 .insert(TypeId::of::<T>(), (color, ranges));
4576 cx.notify();
4577 }
4578
4579 pub fn clear_highlighted_ranges<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
4580 self.highlighted_ranges.remove(&TypeId::of::<T>());
4581 cx.notify();
4582 }
4583
4584 #[cfg(feature = "test-support")]
4585 pub fn all_highlighted_ranges(
4586 &mut self,
4587 cx: &mut ViewContext<Self>,
4588 ) -> Vec<(Range<DisplayPoint>, Color)> {
4589 let snapshot = self.snapshot(cx);
4590 let buffer = &snapshot.buffer_snapshot;
4591 let start = buffer.anchor_before(0);
4592 let end = buffer.anchor_after(buffer.len());
4593 self.highlighted_ranges_in_range(start..end, &snapshot)
4594 }
4595
4596 pub fn highlighted_ranges_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
4597 self.highlighted_ranges
4598 .get(&TypeId::of::<T>())
4599 .map(|(color, ranges)| (*color, ranges.as_slice()))
4600 }
4601
4602 pub fn highlighted_ranges_in_range(
4603 &self,
4604 search_range: Range<Anchor>,
4605 display_snapshot: &DisplaySnapshot,
4606 ) -> Vec<(Range<DisplayPoint>, Color)> {
4607 let mut results = Vec::new();
4608 let buffer = &display_snapshot.buffer_snapshot;
4609 for (color, ranges) in self.highlighted_ranges.values() {
4610 let start_ix = match ranges.binary_search_by(|probe| {
4611 let cmp = probe.end.cmp(&search_range.start, &buffer).unwrap();
4612 if cmp.is_gt() {
4613 Ordering::Greater
4614 } else {
4615 Ordering::Less
4616 }
4617 }) {
4618 Ok(i) | Err(i) => i,
4619 };
4620 for range in &ranges[start_ix..] {
4621 if range.start.cmp(&search_range.end, &buffer).unwrap().is_ge() {
4622 break;
4623 }
4624 let start = range
4625 .start
4626 .to_point(buffer)
4627 .to_display_point(display_snapshot);
4628 let end = range
4629 .end
4630 .to_point(buffer)
4631 .to_display_point(display_snapshot);
4632 results.push((start..end, *color))
4633 }
4634 }
4635 results
4636 }
4637
4638 fn next_blink_epoch(&mut self) -> usize {
4639 self.blink_epoch += 1;
4640 self.blink_epoch
4641 }
4642
4643 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
4644 if !self.focused {
4645 return;
4646 }
4647
4648 self.show_local_cursors = true;
4649 cx.notify();
4650
4651 let epoch = self.next_blink_epoch();
4652 cx.spawn(|this, mut cx| {
4653 let this = this.downgrade();
4654 async move {
4655 Timer::after(CURSOR_BLINK_INTERVAL).await;
4656 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
4657 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
4658 }
4659 }
4660 })
4661 .detach();
4662 }
4663
4664 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
4665 if epoch == self.blink_epoch {
4666 self.blinking_paused = false;
4667 self.blink_cursors(epoch, cx);
4668 }
4669 }
4670
4671 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
4672 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
4673 self.show_local_cursors = !self.show_local_cursors;
4674 cx.notify();
4675
4676 let epoch = self.next_blink_epoch();
4677 cx.spawn(|this, mut cx| {
4678 let this = this.downgrade();
4679 async move {
4680 Timer::after(CURSOR_BLINK_INTERVAL).await;
4681 if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
4682 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
4683 }
4684 }
4685 })
4686 .detach();
4687 }
4688 }
4689
4690 pub fn show_local_cursors(&self) -> bool {
4691 self.show_local_cursors
4692 }
4693
4694 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
4695 self.refresh_active_diagnostics(cx);
4696 cx.notify();
4697 }
4698
4699 fn on_buffer_event(
4700 &mut self,
4701 _: ModelHandle<MultiBuffer>,
4702 event: &language::Event,
4703 cx: &mut ViewContext<Self>,
4704 ) {
4705 match event {
4706 language::Event::Edited => cx.emit(Event::Edited),
4707 language::Event::Dirtied => cx.emit(Event::Dirtied),
4708 language::Event::Saved => cx.emit(Event::Saved),
4709 language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
4710 language::Event::Reloaded => cx.emit(Event::TitleChanged),
4711 language::Event::Closed => cx.emit(Event::Closed),
4712 _ => {}
4713 }
4714 }
4715
4716 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
4717 cx.notify();
4718 }
4719}
4720
4721impl EditorSnapshot {
4722 pub fn is_focused(&self) -> bool {
4723 self.is_focused
4724 }
4725
4726 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
4727 self.placeholder_text.as_ref()
4728 }
4729
4730 pub fn scroll_position(&self) -> Vector2F {
4731 compute_scroll_position(
4732 &self.display_snapshot,
4733 self.scroll_position,
4734 &self.scroll_top_anchor,
4735 )
4736 }
4737}
4738
4739impl Deref for EditorSnapshot {
4740 type Target = DisplaySnapshot;
4741
4742 fn deref(&self) -> &Self::Target {
4743 &self.display_snapshot
4744 }
4745}
4746
4747impl EditorSettings {
4748 #[cfg(any(test, feature = "test-support"))]
4749 pub fn test(cx: &AppContext) -> Self {
4750 use theme::{ContainedLabel, ContainedText, DiagnosticHeader, DiagnosticPathHeader};
4751
4752 Self {
4753 tab_size: 4,
4754 soft_wrap: SoftWrap::None,
4755 style: {
4756 let font_cache: &gpui::FontCache = cx.font_cache();
4757 let font_family_name = Arc::from("Monaco");
4758 let font_properties = Default::default();
4759 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
4760 let font_id = font_cache
4761 .select_font(font_family_id, &font_properties)
4762 .unwrap();
4763 let text = gpui::fonts::TextStyle {
4764 font_family_name,
4765 font_family_id,
4766 font_id,
4767 font_size: 14.,
4768 color: gpui::color::Color::from_u32(0xff0000ff),
4769 font_properties,
4770 underline: None,
4771 };
4772 let default_diagnostic_style = DiagnosticStyle {
4773 message: text.clone().into(),
4774 header: Default::default(),
4775 text_scale_factor: 1.,
4776 };
4777 EditorStyle {
4778 text: text.clone(),
4779 placeholder_text: None,
4780 background: Default::default(),
4781 gutter_background: Default::default(),
4782 gutter_padding_factor: 2.,
4783 active_line_background: Default::default(),
4784 highlighted_line_background: Default::default(),
4785 line_number: Default::default(),
4786 line_number_active: Default::default(),
4787 selection: Default::default(),
4788 guest_selections: Default::default(),
4789 syntax: Default::default(),
4790 diagnostic_path_header: DiagnosticPathHeader {
4791 container: Default::default(),
4792 filename: ContainedText {
4793 container: Default::default(),
4794 text: text.clone(),
4795 },
4796 path: ContainedText {
4797 container: Default::default(),
4798 text: text.clone(),
4799 },
4800 text_scale_factor: 1.,
4801 },
4802 diagnostic_header: DiagnosticHeader {
4803 container: Default::default(),
4804 message: ContainedLabel {
4805 container: Default::default(),
4806 label: text.clone().into(),
4807 },
4808 code: ContainedText {
4809 container: Default::default(),
4810 text: text.clone(),
4811 },
4812 icon_width_factor: 1.,
4813 text_scale_factor: 1.,
4814 },
4815 error_diagnostic: default_diagnostic_style.clone(),
4816 invalid_error_diagnostic: default_diagnostic_style.clone(),
4817 warning_diagnostic: default_diagnostic_style.clone(),
4818 invalid_warning_diagnostic: default_diagnostic_style.clone(),
4819 information_diagnostic: default_diagnostic_style.clone(),
4820 invalid_information_diagnostic: default_diagnostic_style.clone(),
4821 hint_diagnostic: default_diagnostic_style.clone(),
4822 invalid_hint_diagnostic: default_diagnostic_style.clone(),
4823 autocomplete: Default::default(),
4824 }
4825 },
4826 }
4827 }
4828}
4829
4830fn compute_scroll_position(
4831 snapshot: &DisplaySnapshot,
4832 mut scroll_position: Vector2F,
4833 scroll_top_anchor: &Option<Anchor>,
4834) -> Vector2F {
4835 if let Some(anchor) = scroll_top_anchor {
4836 let scroll_top = anchor.to_display_point(snapshot).row() as f32;
4837 scroll_position.set_y(scroll_top + scroll_position.y());
4838 } else {
4839 scroll_position.set_y(0.);
4840 }
4841 scroll_position
4842}
4843
4844#[derive(Copy, Clone)]
4845pub enum Event {
4846 Activate,
4847 Edited,
4848 Blurred,
4849 Dirtied,
4850 Saved,
4851 TitleChanged,
4852 SelectionsChanged,
4853 Closed,
4854}
4855
4856impl Entity for Editor {
4857 type Event = Event;
4858}
4859
4860impl View for Editor {
4861 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
4862 let settings = (self.build_settings)(cx);
4863 self.display_map.update(cx, |map, cx| {
4864 map.set_font(
4865 settings.style.text.font_id,
4866 settings.style.text.font_size,
4867 cx,
4868 )
4869 });
4870 EditorElement::new(self.handle.clone(), settings).boxed()
4871 }
4872
4873 fn ui_name() -> &'static str {
4874 "Editor"
4875 }
4876
4877 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
4878 self.focused = true;
4879 self.blink_cursors(self.blink_epoch, cx);
4880 self.buffer.update(cx, |buffer, cx| {
4881 buffer.finalize_last_transaction(cx);
4882 buffer.set_active_selections(&self.selections, cx)
4883 });
4884 }
4885
4886 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
4887 self.focused = false;
4888 self.show_local_cursors = false;
4889 self.buffer
4890 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
4891 self.hide_context_menu(cx);
4892 cx.emit(Event::Blurred);
4893 cx.notify();
4894 }
4895
4896 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
4897 let mut cx = Self::default_keymap_context();
4898 let mode = match self.mode {
4899 EditorMode::SingleLine => "single_line",
4900 EditorMode::AutoHeight { .. } => "auto_height",
4901 EditorMode::Full => "full",
4902 };
4903 cx.map.insert("mode".into(), mode.into());
4904 match self.context_menu.as_ref() {
4905 Some(ContextMenu::Completions(_)) => {
4906 cx.set.insert("showing_completions".into());
4907 }
4908 Some(ContextMenu::CodeActions(_)) => {
4909 cx.set.insert("showing_code_actions".into());
4910 }
4911 None => {}
4912 }
4913 cx
4914 }
4915}
4916
4917impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
4918 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
4919 let start = self.start.to_point(buffer);
4920 let end = self.end.to_point(buffer);
4921 if self.reversed {
4922 end..start
4923 } else {
4924 start..end
4925 }
4926 }
4927
4928 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
4929 let start = self.start.to_offset(buffer);
4930 let end = self.end.to_offset(buffer);
4931 if self.reversed {
4932 end..start
4933 } else {
4934 start..end
4935 }
4936 }
4937
4938 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
4939 let start = self
4940 .start
4941 .to_point(&map.buffer_snapshot)
4942 .to_display_point(map);
4943 let end = self
4944 .end
4945 .to_point(&map.buffer_snapshot)
4946 .to_display_point(map);
4947 if self.reversed {
4948 end..start
4949 } else {
4950 start..end
4951 }
4952 }
4953
4954 fn spanned_rows(
4955 &self,
4956 include_end_if_at_line_start: bool,
4957 map: &DisplaySnapshot,
4958 ) -> Range<u32> {
4959 let start = self.start.to_point(&map.buffer_snapshot);
4960 let mut end = self.end.to_point(&map.buffer_snapshot);
4961 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
4962 end.row -= 1;
4963 }
4964
4965 let buffer_start = map.prev_line_boundary(start).0;
4966 let buffer_end = map.next_line_boundary(end).0;
4967 buffer_start.row..buffer_end.row + 1
4968 }
4969}
4970
4971impl<T: InvalidationRegion> InvalidationStack<T> {
4972 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
4973 where
4974 S: Clone + ToOffset,
4975 {
4976 while let Some(region) = self.last() {
4977 let all_selections_inside_invalidation_ranges =
4978 if selections.len() == region.ranges().len() {
4979 selections
4980 .iter()
4981 .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
4982 .all(|(selection, invalidation_range)| {
4983 let head = selection.head().to_offset(&buffer);
4984 invalidation_range.start <= head && invalidation_range.end >= head
4985 })
4986 } else {
4987 false
4988 };
4989
4990 if all_selections_inside_invalidation_ranges {
4991 break;
4992 } else {
4993 self.pop();
4994 }
4995 }
4996 }
4997}
4998
4999impl<T> Default for InvalidationStack<T> {
5000 fn default() -> Self {
5001 Self(Default::default())
5002 }
5003}
5004
5005impl<T> Deref for InvalidationStack<T> {
5006 type Target = Vec<T>;
5007
5008 fn deref(&self) -> &Self::Target {
5009 &self.0
5010 }
5011}
5012
5013impl<T> DerefMut for InvalidationStack<T> {
5014 fn deref_mut(&mut self) -> &mut Self::Target {
5015 &mut self.0
5016 }
5017}
5018
5019impl InvalidationRegion for BracketPairState {
5020 fn ranges(&self) -> &[Range<Anchor>] {
5021 &self.ranges
5022 }
5023}
5024
5025impl InvalidationRegion for SnippetState {
5026 fn ranges(&self) -> &[Range<Anchor>] {
5027 &self.ranges[self.active_index]
5028 }
5029}
5030
5031pub fn diagnostic_block_renderer(
5032 diagnostic: Diagnostic,
5033 is_valid: bool,
5034 build_settings: BuildSettings,
5035) -> RenderBlock {
5036 let mut highlighted_lines = Vec::new();
5037 for line in diagnostic.message.lines() {
5038 highlighted_lines.push(highlight_diagnostic_message(line));
5039 }
5040
5041 Arc::new(move |cx: &BlockContext| {
5042 let settings = build_settings(cx);
5043 let style = diagnostic_style(diagnostic.severity, is_valid, &settings.style);
5044 let font_size = (style.text_scale_factor * settings.style.text.font_size).round();
5045 Flex::column()
5046 .with_children(highlighted_lines.iter().map(|(line, highlights)| {
5047 Label::new(
5048 line.clone(),
5049 style.message.clone().with_font_size(font_size),
5050 )
5051 .with_highlights(highlights.clone())
5052 .contained()
5053 .with_margin_left(cx.anchor_x)
5054 .boxed()
5055 }))
5056 .aligned()
5057 .left()
5058 .boxed()
5059 })
5060}
5061
5062pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
5063 let mut message_without_backticks = String::new();
5064 let mut prev_offset = 0;
5065 let mut inside_block = false;
5066 let mut highlights = Vec::new();
5067 for (match_ix, (offset, _)) in message
5068 .match_indices('`')
5069 .chain([(message.len(), "")])
5070 .enumerate()
5071 {
5072 message_without_backticks.push_str(&message[prev_offset..offset]);
5073 if inside_block {
5074 highlights.extend(prev_offset - match_ix..offset - match_ix);
5075 }
5076
5077 inside_block = !inside_block;
5078 prev_offset = offset + 1;
5079 }
5080
5081 (message_without_backticks, highlights)
5082}
5083
5084pub fn diagnostic_style(
5085 severity: DiagnosticSeverity,
5086 valid: bool,
5087 style: &EditorStyle,
5088) -> DiagnosticStyle {
5089 match (severity, valid) {
5090 (DiagnosticSeverity::ERROR, true) => style.error_diagnostic.clone(),
5091 (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic.clone(),
5092 (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic.clone(),
5093 (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic.clone(),
5094 (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic.clone(),
5095 (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic.clone(),
5096 (DiagnosticSeverity::HINT, true) => style.hint_diagnostic.clone(),
5097 (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic.clone(),
5098 _ => DiagnosticStyle {
5099 message: style.text.clone().into(),
5100 header: Default::default(),
5101 text_scale_factor: 1.,
5102 },
5103 }
5104}
5105
5106pub fn settings_builder(
5107 buffer: WeakModelHandle<MultiBuffer>,
5108 settings: watch::Receiver<workspace::Settings>,
5109) -> BuildSettings {
5110 Arc::new(move |cx| {
5111 let settings = settings.borrow();
5112 let font_cache = cx.font_cache();
5113 let font_family_id = settings.buffer_font_family;
5114 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5115 let font_properties = Default::default();
5116 let font_id = font_cache
5117 .select_font(font_family_id, &font_properties)
5118 .unwrap();
5119 let font_size = settings.buffer_font_size;
5120
5121 let mut theme = settings.theme.editor.clone();
5122 theme.text = TextStyle {
5123 color: theme.text.color,
5124 font_family_name,
5125 font_family_id,
5126 font_id,
5127 font_size,
5128 font_properties,
5129 underline: None,
5130 };
5131 let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
5132 let soft_wrap = match settings.soft_wrap(language) {
5133 workspace::settings::SoftWrap::None => SoftWrap::None,
5134 workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5135 workspace::settings::SoftWrap::PreferredLineLength => {
5136 SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
5137 }
5138 };
5139
5140 EditorSettings {
5141 tab_size: settings.tab_size,
5142 soft_wrap,
5143 style: theme,
5144 }
5145 })
5146}
5147
5148pub fn combine_syntax_and_fuzzy_match_highlights(
5149 text: &str,
5150 default_style: HighlightStyle,
5151 syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
5152 match_indices: &[usize],
5153) -> Vec<(Range<usize>, HighlightStyle)> {
5154 let mut result = Vec::new();
5155 let mut match_indices = match_indices.iter().copied().peekable();
5156
5157 for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
5158 {
5159 syntax_highlight.font_properties.weight(Default::default());
5160
5161 // Add highlights for any fuzzy match characters before the next
5162 // syntax highlight range.
5163 while let Some(&match_index) = match_indices.peek() {
5164 if match_index >= range.start {
5165 break;
5166 }
5167 match_indices.next();
5168 let end_index = char_ix_after(match_index, text);
5169 let mut match_style = default_style;
5170 match_style.font_properties.weight(fonts::Weight::BOLD);
5171 result.push((match_index..end_index, match_style));
5172 }
5173
5174 if range.start == usize::MAX {
5175 break;
5176 }
5177
5178 // Add highlights for any fuzzy match characters within the
5179 // syntax highlight range.
5180 let mut offset = range.start;
5181 while let Some(&match_index) = match_indices.peek() {
5182 if match_index >= range.end {
5183 break;
5184 }
5185
5186 match_indices.next();
5187 if match_index > offset {
5188 result.push((offset..match_index, syntax_highlight));
5189 }
5190
5191 let mut end_index = char_ix_after(match_index, text);
5192 while let Some(&next_match_index) = match_indices.peek() {
5193 if next_match_index == end_index && next_match_index < range.end {
5194 end_index = char_ix_after(next_match_index, text);
5195 match_indices.next();
5196 } else {
5197 break;
5198 }
5199 }
5200
5201 let mut match_style = syntax_highlight;
5202 match_style.font_properties.weight(fonts::Weight::BOLD);
5203 result.push((match_index..end_index, match_style));
5204 offset = end_index;
5205 }
5206
5207 if offset < range.end {
5208 result.push((offset..range.end, syntax_highlight));
5209 }
5210 }
5211
5212 fn char_ix_after(ix: usize, text: &str) -> usize {
5213 ix + text[ix..].chars().next().unwrap().len_utf8()
5214 }
5215
5216 result
5217}
5218
5219fn styled_runs_for_completion_label<'a>(
5220 label: &'a CompletionLabel,
5221 default_color: Color,
5222 syntax_theme: &'a theme::SyntaxTheme,
5223) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
5224 const MUTED_OPACITY: usize = 165;
5225
5226 let mut muted_default_style = HighlightStyle {
5227 color: default_color,
5228 ..Default::default()
5229 };
5230 muted_default_style.color.a = ((default_color.a as usize * MUTED_OPACITY) / 255) as u8;
5231
5232 let mut prev_end = label.filter_range.end;
5233 label
5234 .runs
5235 .iter()
5236 .enumerate()
5237 .flat_map(move |(ix, (range, highlight_id))| {
5238 let style = if let Some(style) = highlight_id.style(syntax_theme) {
5239 style
5240 } else {
5241 return Default::default();
5242 };
5243 let mut muted_style = style.clone();
5244 muted_style.color.a = ((style.color.a as usize * MUTED_OPACITY) / 255) as u8;
5245
5246 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
5247 if range.start >= label.filter_range.end {
5248 if range.start > prev_end {
5249 runs.push((prev_end..range.start, muted_default_style));
5250 }
5251 runs.push((range.clone(), muted_style));
5252 } else if range.end <= label.filter_range.end {
5253 runs.push((range.clone(), style));
5254 } else {
5255 runs.push((range.start..label.filter_range.end, style));
5256 runs.push((label.filter_range.end..range.end, muted_style));
5257 }
5258 prev_end = cmp::max(prev_end, range.end);
5259
5260 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
5261 runs.push((prev_end..label.text.len(), muted_default_style));
5262 }
5263
5264 runs
5265 })
5266}
5267
5268#[cfg(test)]
5269mod tests {
5270 use super::*;
5271 use language::LanguageConfig;
5272 use lsp::FakeLanguageServer;
5273 use project::{FakeFs, ProjectPath};
5274 use std::{cell::RefCell, rc::Rc, time::Instant};
5275 use text::Point;
5276 use unindent::Unindent;
5277 use util::test::sample_text;
5278
5279 #[gpui::test]
5280 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
5281 let mut now = Instant::now();
5282 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
5283 let group_interval = buffer.read(cx).transaction_group_interval();
5284 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5285 let settings = EditorSettings::test(cx);
5286 let (_, editor) = cx.add_window(Default::default(), |cx| {
5287 build_editor(buffer.clone(), settings, cx)
5288 });
5289
5290 editor.update(cx, |editor, cx| {
5291 editor.start_transaction_at(now, cx);
5292 editor.select_ranges([2..4], None, cx);
5293 editor.insert("cd", cx);
5294 editor.end_transaction_at(now, cx);
5295 assert_eq!(editor.text(cx), "12cd56");
5296 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
5297
5298 editor.start_transaction_at(now, cx);
5299 editor.select_ranges([4..5], None, cx);
5300 editor.insert("e", cx);
5301 editor.end_transaction_at(now, cx);
5302 assert_eq!(editor.text(cx), "12cde6");
5303 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5304
5305 now += group_interval + Duration::from_millis(1);
5306 editor.select_ranges([2..2], None, cx);
5307
5308 // Simulate an edit in another editor
5309 buffer.update(cx, |buffer, cx| {
5310 buffer.start_transaction_at(now, cx);
5311 buffer.edit([0..1], "a", cx);
5312 buffer.edit([1..1], "b", cx);
5313 buffer.end_transaction_at(now, cx);
5314 });
5315
5316 assert_eq!(editor.text(cx), "ab2cde6");
5317 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
5318
5319 // Last transaction happened past the group interval in a different editor.
5320 // Undo it individually and don't restore selections.
5321 editor.undo(&Undo, cx);
5322 assert_eq!(editor.text(cx), "12cde6");
5323 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
5324
5325 // First two transactions happened within the group interval in this editor.
5326 // Undo them together and restore selections.
5327 editor.undo(&Undo, cx);
5328 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
5329 assert_eq!(editor.text(cx), "123456");
5330 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
5331
5332 // Redo the first two transactions together.
5333 editor.redo(&Redo, cx);
5334 assert_eq!(editor.text(cx), "12cde6");
5335 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5336
5337 // Redo the last transaction on its own.
5338 editor.redo(&Redo, cx);
5339 assert_eq!(editor.text(cx), "ab2cde6");
5340 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
5341
5342 // Test empty transactions.
5343 editor.start_transaction_at(now, cx);
5344 editor.end_transaction_at(now, cx);
5345 editor.undo(&Undo, cx);
5346 assert_eq!(editor.text(cx), "12cde6");
5347 });
5348 }
5349
5350 #[gpui::test]
5351 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
5352 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5353 let settings = EditorSettings::test(cx);
5354 let (_, editor) =
5355 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5356
5357 editor.update(cx, |view, cx| {
5358 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5359 });
5360
5361 assert_eq!(
5362 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5363 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5364 );
5365
5366 editor.update(cx, |view, cx| {
5367 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5368 });
5369
5370 assert_eq!(
5371 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5372 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5373 );
5374
5375 editor.update(cx, |view, cx| {
5376 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5377 });
5378
5379 assert_eq!(
5380 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5381 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5382 );
5383
5384 editor.update(cx, |view, cx| {
5385 view.end_selection(cx);
5386 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5387 });
5388
5389 assert_eq!(
5390 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5391 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
5392 );
5393
5394 editor.update(cx, |view, cx| {
5395 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
5396 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
5397 });
5398
5399 assert_eq!(
5400 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5401 [
5402 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
5403 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
5404 ]
5405 );
5406
5407 editor.update(cx, |view, cx| {
5408 view.end_selection(cx);
5409 });
5410
5411 assert_eq!(
5412 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5413 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
5414 );
5415 }
5416
5417 #[gpui::test]
5418 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
5419 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5420 let settings = EditorSettings::test(cx);
5421 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5422
5423 view.update(cx, |view, cx| {
5424 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5425 assert_eq!(
5426 view.selected_display_ranges(cx),
5427 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5428 );
5429 });
5430
5431 view.update(cx, |view, cx| {
5432 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5433 assert_eq!(
5434 view.selected_display_ranges(cx),
5435 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5436 );
5437 });
5438
5439 view.update(cx, |view, cx| {
5440 view.cancel(&Cancel, cx);
5441 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5442 assert_eq!(
5443 view.selected_display_ranges(cx),
5444 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
5445 );
5446 });
5447 }
5448
5449 #[gpui::test]
5450 fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
5451 cx.add_window(Default::default(), |cx| {
5452 use workspace::ItemView;
5453 let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
5454 let settings = EditorSettings::test(&cx);
5455 let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
5456 let mut editor = build_editor(buffer.clone(), settings, cx);
5457 editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
5458
5459 // Move the cursor a small distance.
5460 // Nothing is added to the navigation history.
5461 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
5462 editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
5463 assert!(nav_history.borrow_mut().pop_backward().is_none());
5464
5465 // Move the cursor a large distance.
5466 // The history can jump back to the previous position.
5467 editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
5468 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
5469 editor.navigate(nav_entry.data.unwrap(), cx);
5470 assert_eq!(nav_entry.item_view.id(), cx.view_id());
5471 assert_eq!(
5472 editor.selected_display_ranges(cx),
5473 &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
5474 );
5475
5476 // Move the cursor a small distance via the mouse.
5477 // Nothing is added to the navigation history.
5478 editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
5479 editor.end_selection(cx);
5480 assert_eq!(
5481 editor.selected_display_ranges(cx),
5482 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
5483 );
5484 assert!(nav_history.borrow_mut().pop_backward().is_none());
5485
5486 // Move the cursor a large distance via the mouse.
5487 // The history can jump back to the previous position.
5488 editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
5489 editor.end_selection(cx);
5490 assert_eq!(
5491 editor.selected_display_ranges(cx),
5492 &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
5493 );
5494 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
5495 editor.navigate(nav_entry.data.unwrap(), cx);
5496 assert_eq!(nav_entry.item_view.id(), cx.view_id());
5497 assert_eq!(
5498 editor.selected_display_ranges(cx),
5499 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
5500 );
5501
5502 editor
5503 });
5504 }
5505
5506 #[gpui::test]
5507 fn test_cancel(cx: &mut gpui::MutableAppContext) {
5508 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5509 let settings = EditorSettings::test(cx);
5510 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5511
5512 view.update(cx, |view, cx| {
5513 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
5514 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
5515 view.end_selection(cx);
5516
5517 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
5518 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
5519 view.end_selection(cx);
5520 assert_eq!(
5521 view.selected_display_ranges(cx),
5522 [
5523 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5524 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
5525 ]
5526 );
5527 });
5528
5529 view.update(cx, |view, cx| {
5530 view.cancel(&Cancel, cx);
5531 assert_eq!(
5532 view.selected_display_ranges(cx),
5533 [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
5534 );
5535 });
5536
5537 view.update(cx, |view, cx| {
5538 view.cancel(&Cancel, cx);
5539 assert_eq!(
5540 view.selected_display_ranges(cx),
5541 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
5542 );
5543 });
5544 }
5545
5546 #[gpui::test]
5547 fn test_fold(cx: &mut gpui::MutableAppContext) {
5548 let buffer = MultiBuffer::build_simple(
5549 &"
5550 impl Foo {
5551 // Hello!
5552
5553 fn a() {
5554 1
5555 }
5556
5557 fn b() {
5558 2
5559 }
5560
5561 fn c() {
5562 3
5563 }
5564 }
5565 "
5566 .unindent(),
5567 cx,
5568 );
5569 let settings = EditorSettings::test(&cx);
5570 let (_, view) = cx.add_window(Default::default(), |cx| {
5571 build_editor(buffer.clone(), settings, cx)
5572 });
5573
5574 view.update(cx, |view, cx| {
5575 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
5576 view.fold(&Fold, cx);
5577 assert_eq!(
5578 view.display_text(cx),
5579 "
5580 impl Foo {
5581 // Hello!
5582
5583 fn a() {
5584 1
5585 }
5586
5587 fn b() {…
5588 }
5589
5590 fn c() {…
5591 }
5592 }
5593 "
5594 .unindent(),
5595 );
5596
5597 view.fold(&Fold, cx);
5598 assert_eq!(
5599 view.display_text(cx),
5600 "
5601 impl Foo {…
5602 }
5603 "
5604 .unindent(),
5605 );
5606
5607 view.unfold(&Unfold, cx);
5608 assert_eq!(
5609 view.display_text(cx),
5610 "
5611 impl Foo {
5612 // Hello!
5613
5614 fn a() {
5615 1
5616 }
5617
5618 fn b() {…
5619 }
5620
5621 fn c() {…
5622 }
5623 }
5624 "
5625 .unindent(),
5626 );
5627
5628 view.unfold(&Unfold, cx);
5629 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
5630 });
5631 }
5632
5633 #[gpui::test]
5634 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
5635 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5636 let settings = EditorSettings::test(&cx);
5637 let (_, view) = cx.add_window(Default::default(), |cx| {
5638 build_editor(buffer.clone(), settings, cx)
5639 });
5640
5641 buffer.update(cx, |buffer, cx| {
5642 buffer.edit(
5643 vec![
5644 Point::new(1, 0)..Point::new(1, 0),
5645 Point::new(1, 1)..Point::new(1, 1),
5646 ],
5647 "\t",
5648 cx,
5649 );
5650 });
5651
5652 view.update(cx, |view, cx| {
5653 assert_eq!(
5654 view.selected_display_ranges(cx),
5655 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
5656 );
5657
5658 view.move_down(&MoveDown, cx);
5659 assert_eq!(
5660 view.selected_display_ranges(cx),
5661 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
5662 );
5663
5664 view.move_right(&MoveRight, cx);
5665 assert_eq!(
5666 view.selected_display_ranges(cx),
5667 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
5668 );
5669
5670 view.move_left(&MoveLeft, cx);
5671 assert_eq!(
5672 view.selected_display_ranges(cx),
5673 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
5674 );
5675
5676 view.move_up(&MoveUp, cx);
5677 assert_eq!(
5678 view.selected_display_ranges(cx),
5679 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
5680 );
5681
5682 view.move_to_end(&MoveToEnd, cx);
5683 assert_eq!(
5684 view.selected_display_ranges(cx),
5685 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
5686 );
5687
5688 view.move_to_beginning(&MoveToBeginning, cx);
5689 assert_eq!(
5690 view.selected_display_ranges(cx),
5691 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
5692 );
5693
5694 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
5695 view.select_to_beginning(&SelectToBeginning, cx);
5696 assert_eq!(
5697 view.selected_display_ranges(cx),
5698 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
5699 );
5700
5701 view.select_to_end(&SelectToEnd, cx);
5702 assert_eq!(
5703 view.selected_display_ranges(cx),
5704 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
5705 );
5706 });
5707 }
5708
5709 #[gpui::test]
5710 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
5711 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
5712 let settings = EditorSettings::test(&cx);
5713 let (_, view) = cx.add_window(Default::default(), |cx| {
5714 build_editor(buffer.clone(), settings, cx)
5715 });
5716
5717 assert_eq!('ⓐ'.len_utf8(), 3);
5718 assert_eq!('α'.len_utf8(), 2);
5719
5720 view.update(cx, |view, cx| {
5721 view.fold_ranges(
5722 vec![
5723 Point::new(0, 6)..Point::new(0, 12),
5724 Point::new(1, 2)..Point::new(1, 4),
5725 Point::new(2, 4)..Point::new(2, 8),
5726 ],
5727 cx,
5728 );
5729 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
5730
5731 view.move_right(&MoveRight, cx);
5732 assert_eq!(
5733 view.selected_display_ranges(cx),
5734 &[empty_range(0, "ⓐ".len())]
5735 );
5736 view.move_right(&MoveRight, cx);
5737 assert_eq!(
5738 view.selected_display_ranges(cx),
5739 &[empty_range(0, "ⓐⓑ".len())]
5740 );
5741 view.move_right(&MoveRight, cx);
5742 assert_eq!(
5743 view.selected_display_ranges(cx),
5744 &[empty_range(0, "ⓐⓑ…".len())]
5745 );
5746
5747 view.move_down(&MoveDown, cx);
5748 assert_eq!(
5749 view.selected_display_ranges(cx),
5750 &[empty_range(1, "ab…".len())]
5751 );
5752 view.move_left(&MoveLeft, cx);
5753 assert_eq!(
5754 view.selected_display_ranges(cx),
5755 &[empty_range(1, "ab".len())]
5756 );
5757 view.move_left(&MoveLeft, cx);
5758 assert_eq!(
5759 view.selected_display_ranges(cx),
5760 &[empty_range(1, "a".len())]
5761 );
5762
5763 view.move_down(&MoveDown, cx);
5764 assert_eq!(
5765 view.selected_display_ranges(cx),
5766 &[empty_range(2, "α".len())]
5767 );
5768 view.move_right(&MoveRight, cx);
5769 assert_eq!(
5770 view.selected_display_ranges(cx),
5771 &[empty_range(2, "αβ".len())]
5772 );
5773 view.move_right(&MoveRight, cx);
5774 assert_eq!(
5775 view.selected_display_ranges(cx),
5776 &[empty_range(2, "αβ…".len())]
5777 );
5778 view.move_right(&MoveRight, cx);
5779 assert_eq!(
5780 view.selected_display_ranges(cx),
5781 &[empty_range(2, "αβ…ε".len())]
5782 );
5783
5784 view.move_up(&MoveUp, cx);
5785 assert_eq!(
5786 view.selected_display_ranges(cx),
5787 &[empty_range(1, "ab…e".len())]
5788 );
5789 view.move_up(&MoveUp, cx);
5790 assert_eq!(
5791 view.selected_display_ranges(cx),
5792 &[empty_range(0, "ⓐⓑ…ⓔ".len())]
5793 );
5794 view.move_left(&MoveLeft, cx);
5795 assert_eq!(
5796 view.selected_display_ranges(cx),
5797 &[empty_range(0, "ⓐⓑ…".len())]
5798 );
5799 view.move_left(&MoveLeft, cx);
5800 assert_eq!(
5801 view.selected_display_ranges(cx),
5802 &[empty_range(0, "ⓐⓑ".len())]
5803 );
5804 view.move_left(&MoveLeft, cx);
5805 assert_eq!(
5806 view.selected_display_ranges(cx),
5807 &[empty_range(0, "ⓐ".len())]
5808 );
5809 });
5810 }
5811
5812 #[gpui::test]
5813 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
5814 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
5815 let settings = EditorSettings::test(&cx);
5816 let (_, view) = cx.add_window(Default::default(), |cx| {
5817 build_editor(buffer.clone(), settings, cx)
5818 });
5819 view.update(cx, |view, cx| {
5820 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
5821 view.move_down(&MoveDown, cx);
5822 assert_eq!(
5823 view.selected_display_ranges(cx),
5824 &[empty_range(1, "abcd".len())]
5825 );
5826
5827 view.move_down(&MoveDown, cx);
5828 assert_eq!(
5829 view.selected_display_ranges(cx),
5830 &[empty_range(2, "αβγ".len())]
5831 );
5832
5833 view.move_down(&MoveDown, cx);
5834 assert_eq!(
5835 view.selected_display_ranges(cx),
5836 &[empty_range(3, "abcd".len())]
5837 );
5838
5839 view.move_down(&MoveDown, cx);
5840 assert_eq!(
5841 view.selected_display_ranges(cx),
5842 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
5843 );
5844
5845 view.move_up(&MoveUp, cx);
5846 assert_eq!(
5847 view.selected_display_ranges(cx),
5848 &[empty_range(3, "abcd".len())]
5849 );
5850
5851 view.move_up(&MoveUp, cx);
5852 assert_eq!(
5853 view.selected_display_ranges(cx),
5854 &[empty_range(2, "αβγ".len())]
5855 );
5856 });
5857 }
5858
5859 #[gpui::test]
5860 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
5861 let buffer = MultiBuffer::build_simple("abc\n def", cx);
5862 let settings = EditorSettings::test(&cx);
5863 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5864 view.update(cx, |view, cx| {
5865 view.select_display_ranges(
5866 &[
5867 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5868 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
5869 ],
5870 cx,
5871 );
5872 });
5873
5874 view.update(cx, |view, cx| {
5875 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
5876 assert_eq!(
5877 view.selected_display_ranges(cx),
5878 &[
5879 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5880 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5881 ]
5882 );
5883 });
5884
5885 view.update(cx, |view, cx| {
5886 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
5887 assert_eq!(
5888 view.selected_display_ranges(cx),
5889 &[
5890 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5891 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5892 ]
5893 );
5894 });
5895
5896 view.update(cx, |view, cx| {
5897 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
5898 assert_eq!(
5899 view.selected_display_ranges(cx),
5900 &[
5901 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5902 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5903 ]
5904 );
5905 });
5906
5907 view.update(cx, |view, cx| {
5908 view.move_to_end_of_line(&MoveToEndOfLine, cx);
5909 assert_eq!(
5910 view.selected_display_ranges(cx),
5911 &[
5912 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5913 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5914 ]
5915 );
5916 });
5917
5918 // Moving to the end of line again is a no-op.
5919 view.update(cx, |view, cx| {
5920 view.move_to_end_of_line(&MoveToEndOfLine, cx);
5921 assert_eq!(
5922 view.selected_display_ranges(cx),
5923 &[
5924 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5925 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5926 ]
5927 );
5928 });
5929
5930 view.update(cx, |view, cx| {
5931 view.move_left(&MoveLeft, cx);
5932 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
5933 assert_eq!(
5934 view.selected_display_ranges(cx),
5935 &[
5936 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
5937 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
5938 ]
5939 );
5940 });
5941
5942 view.update(cx, |view, cx| {
5943 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
5944 assert_eq!(
5945 view.selected_display_ranges(cx),
5946 &[
5947 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
5948 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
5949 ]
5950 );
5951 });
5952
5953 view.update(cx, |view, cx| {
5954 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
5955 assert_eq!(
5956 view.selected_display_ranges(cx),
5957 &[
5958 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
5959 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
5960 ]
5961 );
5962 });
5963
5964 view.update(cx, |view, cx| {
5965 view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
5966 assert_eq!(
5967 view.selected_display_ranges(cx),
5968 &[
5969 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5970 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
5971 ]
5972 );
5973 });
5974
5975 view.update(cx, |view, cx| {
5976 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
5977 assert_eq!(view.display_text(cx), "ab\n de");
5978 assert_eq!(
5979 view.selected_display_ranges(cx),
5980 &[
5981 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5982 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
5983 ]
5984 );
5985 });
5986
5987 view.update(cx, |view, cx| {
5988 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
5989 assert_eq!(view.display_text(cx), "\n");
5990 assert_eq!(
5991 view.selected_display_ranges(cx),
5992 &[
5993 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5994 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5995 ]
5996 );
5997 });
5998 }
5999
6000 #[gpui::test]
6001 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
6002 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
6003 let settings = EditorSettings::test(&cx);
6004 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6005 view.update(cx, |view, cx| {
6006 view.select_display_ranges(
6007 &[
6008 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6009 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
6010 ],
6011 cx,
6012 );
6013 });
6014
6015 view.update(cx, |view, cx| {
6016 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6017 assert_eq!(
6018 view.selected_display_ranges(cx),
6019 &[
6020 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6021 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6022 ]
6023 );
6024 });
6025
6026 view.update(cx, |view, cx| {
6027 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6028 assert_eq!(
6029 view.selected_display_ranges(cx),
6030 &[
6031 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6032 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
6033 ]
6034 );
6035 });
6036
6037 view.update(cx, |view, cx| {
6038 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6039 assert_eq!(
6040 view.selected_display_ranges(cx),
6041 &[
6042 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
6043 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6044 ]
6045 );
6046 });
6047
6048 view.update(cx, |view, cx| {
6049 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6050 assert_eq!(
6051 view.selected_display_ranges(cx),
6052 &[
6053 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6054 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6055 ]
6056 );
6057 });
6058
6059 view.update(cx, |view, cx| {
6060 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6061 assert_eq!(
6062 view.selected_display_ranges(cx),
6063 &[
6064 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6065 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
6066 ]
6067 );
6068 });
6069
6070 view.update(cx, |view, cx| {
6071 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6072 assert_eq!(
6073 view.selected_display_ranges(cx),
6074 &[
6075 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6076 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
6077 ]
6078 );
6079 });
6080
6081 view.update(cx, |view, cx| {
6082 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6083 assert_eq!(
6084 view.selected_display_ranges(cx),
6085 &[
6086 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6087 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6088 ]
6089 );
6090 });
6091
6092 view.update(cx, |view, cx| {
6093 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6094 assert_eq!(
6095 view.selected_display_ranges(cx),
6096 &[
6097 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6098 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6099 ]
6100 );
6101 });
6102
6103 view.update(cx, |view, cx| {
6104 view.move_right(&MoveRight, cx);
6105 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6106 assert_eq!(
6107 view.selected_display_ranges(cx),
6108 &[
6109 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6110 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6111 ]
6112 );
6113 });
6114
6115 view.update(cx, |view, cx| {
6116 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6117 assert_eq!(
6118 view.selected_display_ranges(cx),
6119 &[
6120 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
6121 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
6122 ]
6123 );
6124 });
6125
6126 view.update(cx, |view, cx| {
6127 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
6128 assert_eq!(
6129 view.selected_display_ranges(cx),
6130 &[
6131 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6132 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6133 ]
6134 );
6135 });
6136 }
6137
6138 #[gpui::test]
6139 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
6140 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
6141 let settings = EditorSettings::test(&cx);
6142 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6143
6144 view.update(cx, |view, cx| {
6145 view.set_wrap_width(Some(140.), cx);
6146 assert_eq!(
6147 view.display_text(cx),
6148 "use one::{\n two::three::\n four::five\n};"
6149 );
6150
6151 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
6152
6153 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6154 assert_eq!(
6155 view.selected_display_ranges(cx),
6156 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
6157 );
6158
6159 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6160 assert_eq!(
6161 view.selected_display_ranges(cx),
6162 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6163 );
6164
6165 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6166 assert_eq!(
6167 view.selected_display_ranges(cx),
6168 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6169 );
6170
6171 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6172 assert_eq!(
6173 view.selected_display_ranges(cx),
6174 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
6175 );
6176
6177 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6178 assert_eq!(
6179 view.selected_display_ranges(cx),
6180 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6181 );
6182
6183 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6184 assert_eq!(
6185 view.selected_display_ranges(cx),
6186 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6187 );
6188 });
6189 }
6190
6191 #[gpui::test]
6192 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
6193 let buffer = MultiBuffer::build_simple("one two three four", cx);
6194 let settings = EditorSettings::test(&cx);
6195 let (_, view) = cx.add_window(Default::default(), |cx| {
6196 build_editor(buffer.clone(), settings, cx)
6197 });
6198
6199 view.update(cx, |view, cx| {
6200 view.select_display_ranges(
6201 &[
6202 // an empty selection - the preceding word fragment is deleted
6203 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6204 // characters selected - they are deleted
6205 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
6206 ],
6207 cx,
6208 );
6209 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
6210 });
6211
6212 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
6213
6214 view.update(cx, |view, cx| {
6215 view.select_display_ranges(
6216 &[
6217 // an empty selection - the following word fragment is deleted
6218 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6219 // characters selected - they are deleted
6220 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
6221 ],
6222 cx,
6223 );
6224 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
6225 });
6226
6227 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
6228 }
6229
6230 #[gpui::test]
6231 fn test_newline(cx: &mut gpui::MutableAppContext) {
6232 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
6233 let settings = EditorSettings::test(&cx);
6234 let (_, view) = cx.add_window(Default::default(), |cx| {
6235 build_editor(buffer.clone(), settings, cx)
6236 });
6237
6238 view.update(cx, |view, cx| {
6239 view.select_display_ranges(
6240 &[
6241 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6242 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6243 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
6244 ],
6245 cx,
6246 );
6247
6248 view.newline(&Newline, cx);
6249 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
6250 });
6251 }
6252
6253 #[gpui::test]
6254 fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
6255 let buffer = MultiBuffer::build_simple(
6256 "
6257 a
6258 b(
6259 X
6260 )
6261 c(
6262 X
6263 )
6264 "
6265 .unindent()
6266 .as_str(),
6267 cx,
6268 );
6269
6270 let settings = EditorSettings::test(&cx);
6271 let (_, editor) = cx.add_window(Default::default(), |cx| {
6272 let mut editor = build_editor(buffer.clone(), settings, cx);
6273 editor.select_ranges(
6274 [
6275 Point::new(2, 4)..Point::new(2, 5),
6276 Point::new(5, 4)..Point::new(5, 5),
6277 ],
6278 None,
6279 cx,
6280 );
6281 editor
6282 });
6283
6284 // Edit the buffer directly, deleting ranges surrounding the editor's selections
6285 buffer.update(cx, |buffer, cx| {
6286 buffer.edit(
6287 [
6288 Point::new(1, 2)..Point::new(3, 0),
6289 Point::new(4, 2)..Point::new(6, 0),
6290 ],
6291 "",
6292 cx,
6293 );
6294 assert_eq!(
6295 buffer.read(cx).text(),
6296 "
6297 a
6298 b()
6299 c()
6300 "
6301 .unindent()
6302 );
6303 });
6304
6305 editor.update(cx, |editor, cx| {
6306 assert_eq!(
6307 editor.selected_ranges(cx),
6308 &[
6309 Point::new(1, 2)..Point::new(1, 2),
6310 Point::new(2, 2)..Point::new(2, 2),
6311 ],
6312 );
6313
6314 editor.newline(&Newline, cx);
6315 assert_eq!(
6316 editor.text(cx),
6317 "
6318 a
6319 b(
6320 )
6321 c(
6322 )
6323 "
6324 .unindent()
6325 );
6326
6327 // The selections are moved after the inserted newlines
6328 assert_eq!(
6329 editor.selected_ranges(cx),
6330 &[
6331 Point::new(2, 0)..Point::new(2, 0),
6332 Point::new(4, 0)..Point::new(4, 0),
6333 ],
6334 );
6335 });
6336 }
6337
6338 #[gpui::test]
6339 fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
6340 let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
6341
6342 let settings = EditorSettings::test(&cx);
6343 let (_, editor) = cx.add_window(Default::default(), |cx| {
6344 let mut editor = build_editor(buffer.clone(), settings, cx);
6345 editor.select_ranges([3..4, 11..12, 19..20], None, cx);
6346 editor
6347 });
6348
6349 // Edit the buffer directly, deleting ranges surrounding the editor's selections
6350 buffer.update(cx, |buffer, cx| {
6351 buffer.edit([2..5, 10..13, 18..21], "", cx);
6352 assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
6353 });
6354
6355 editor.update(cx, |editor, cx| {
6356 assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
6357
6358 editor.insert("Z", cx);
6359 assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
6360
6361 // The selections are moved after the inserted characters
6362 assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
6363 });
6364 }
6365
6366 #[gpui::test]
6367 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
6368 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
6369 let settings = EditorSettings::test(&cx);
6370 let (_, view) = cx.add_window(Default::default(), |cx| {
6371 build_editor(buffer.clone(), settings, cx)
6372 });
6373
6374 view.update(cx, |view, cx| {
6375 // two selections on the same line
6376 view.select_display_ranges(
6377 &[
6378 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
6379 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
6380 ],
6381 cx,
6382 );
6383
6384 // indent from mid-tabstop to full tabstop
6385 view.tab(&Tab, cx);
6386 assert_eq!(view.text(cx), " one two\nthree\n four");
6387 assert_eq!(
6388 view.selected_display_ranges(cx),
6389 &[
6390 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6391 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
6392 ]
6393 );
6394
6395 // outdent from 1 tabstop to 0 tabstops
6396 view.outdent(&Outdent, cx);
6397 assert_eq!(view.text(cx), "one two\nthree\n four");
6398 assert_eq!(
6399 view.selected_display_ranges(cx),
6400 &[
6401 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
6402 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
6403 ]
6404 );
6405
6406 // select across line ending
6407 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
6408
6409 // indent and outdent affect only the preceding line
6410 view.tab(&Tab, cx);
6411 assert_eq!(view.text(cx), "one two\n three\n four");
6412 assert_eq!(
6413 view.selected_display_ranges(cx),
6414 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
6415 );
6416 view.outdent(&Outdent, cx);
6417 assert_eq!(view.text(cx), "one two\nthree\n four");
6418 assert_eq!(
6419 view.selected_display_ranges(cx),
6420 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
6421 );
6422
6423 // Ensure that indenting/outdenting works when the cursor is at column 0.
6424 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6425 view.tab(&Tab, cx);
6426 assert_eq!(view.text(cx), "one two\n three\n four");
6427 assert_eq!(
6428 view.selected_display_ranges(cx),
6429 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6430 );
6431
6432 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6433 view.outdent(&Outdent, cx);
6434 assert_eq!(view.text(cx), "one two\nthree\n four");
6435 assert_eq!(
6436 view.selected_display_ranges(cx),
6437 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6438 );
6439 });
6440 }
6441
6442 #[gpui::test]
6443 fn test_backspace(cx: &mut gpui::MutableAppContext) {
6444 let buffer =
6445 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
6446 let settings = EditorSettings::test(&cx);
6447 let (_, view) = cx.add_window(Default::default(), |cx| {
6448 build_editor(buffer.clone(), settings, cx)
6449 });
6450
6451 view.update(cx, |view, cx| {
6452 view.select_display_ranges(
6453 &[
6454 // an empty selection - the preceding character is deleted
6455 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6456 // one character selected - it is deleted
6457 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6458 // a line suffix selected - it is deleted
6459 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
6460 ],
6461 cx,
6462 );
6463 view.backspace(&Backspace, cx);
6464 });
6465
6466 assert_eq!(
6467 buffer.read(cx).read(cx).text(),
6468 "oe two three\nfou five six\nseven ten\n"
6469 );
6470 }
6471
6472 #[gpui::test]
6473 fn test_delete(cx: &mut gpui::MutableAppContext) {
6474 let buffer =
6475 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
6476 let settings = EditorSettings::test(&cx);
6477 let (_, view) = cx.add_window(Default::default(), |cx| {
6478 build_editor(buffer.clone(), settings, cx)
6479 });
6480
6481 view.update(cx, |view, cx| {
6482 view.select_display_ranges(
6483 &[
6484 // an empty selection - the following character is deleted
6485 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6486 // one character selected - it is deleted
6487 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
6488 // a line suffix selected - it is deleted
6489 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
6490 ],
6491 cx,
6492 );
6493 view.delete(&Delete, cx);
6494 });
6495
6496 assert_eq!(
6497 buffer.read(cx).read(cx).text(),
6498 "on two three\nfou five six\nseven ten\n"
6499 );
6500 }
6501
6502 #[gpui::test]
6503 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
6504 let settings = EditorSettings::test(&cx);
6505 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6506 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6507 view.update(cx, |view, cx| {
6508 view.select_display_ranges(
6509 &[
6510 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6511 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
6512 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6513 ],
6514 cx,
6515 );
6516 view.delete_line(&DeleteLine, cx);
6517 assert_eq!(view.display_text(cx), "ghi");
6518 assert_eq!(
6519 view.selected_display_ranges(cx),
6520 vec![
6521 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6522 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
6523 ]
6524 );
6525 });
6526
6527 let settings = EditorSettings::test(&cx);
6528 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6529 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6530 view.update(cx, |view, cx| {
6531 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
6532 view.delete_line(&DeleteLine, cx);
6533 assert_eq!(view.display_text(cx), "ghi\n");
6534 assert_eq!(
6535 view.selected_display_ranges(cx),
6536 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
6537 );
6538 });
6539 }
6540
6541 #[gpui::test]
6542 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
6543 let settings = EditorSettings::test(&cx);
6544 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6545 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6546 view.update(cx, |view, cx| {
6547 view.select_display_ranges(
6548 &[
6549 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6550 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6551 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6552 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6553 ],
6554 cx,
6555 );
6556 view.duplicate_line(&DuplicateLine, cx);
6557 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
6558 assert_eq!(
6559 view.selected_display_ranges(cx),
6560 vec![
6561 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
6562 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6563 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6564 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
6565 ]
6566 );
6567 });
6568
6569 let settings = EditorSettings::test(&cx);
6570 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
6571 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6572 view.update(cx, |view, cx| {
6573 view.select_display_ranges(
6574 &[
6575 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
6576 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
6577 ],
6578 cx,
6579 );
6580 view.duplicate_line(&DuplicateLine, cx);
6581 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
6582 assert_eq!(
6583 view.selected_display_ranges(cx),
6584 vec![
6585 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
6586 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
6587 ]
6588 );
6589 });
6590 }
6591
6592 #[gpui::test]
6593 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
6594 let settings = EditorSettings::test(&cx);
6595 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
6596 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6597 view.update(cx, |view, cx| {
6598 view.fold_ranges(
6599 vec![
6600 Point::new(0, 2)..Point::new(1, 2),
6601 Point::new(2, 3)..Point::new(4, 1),
6602 Point::new(7, 0)..Point::new(8, 4),
6603 ],
6604 cx,
6605 );
6606 view.select_display_ranges(
6607 &[
6608 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6609 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6610 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6611 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
6612 ],
6613 cx,
6614 );
6615 assert_eq!(
6616 view.display_text(cx),
6617 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
6618 );
6619
6620 view.move_line_up(&MoveLineUp, cx);
6621 assert_eq!(
6622 view.display_text(cx),
6623 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
6624 );
6625 assert_eq!(
6626 view.selected_display_ranges(cx),
6627 vec![
6628 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6629 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6630 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
6631 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
6632 ]
6633 );
6634 });
6635
6636 view.update(cx, |view, cx| {
6637 view.move_line_down(&MoveLineDown, cx);
6638 assert_eq!(
6639 view.display_text(cx),
6640 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
6641 );
6642 assert_eq!(
6643 view.selected_display_ranges(cx),
6644 vec![
6645 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6646 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6647 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6648 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
6649 ]
6650 );
6651 });
6652
6653 view.update(cx, |view, cx| {
6654 view.move_line_down(&MoveLineDown, cx);
6655 assert_eq!(
6656 view.display_text(cx),
6657 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
6658 );
6659 assert_eq!(
6660 view.selected_display_ranges(cx),
6661 vec![
6662 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6663 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
6664 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
6665 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
6666 ]
6667 );
6668 });
6669
6670 view.update(cx, |view, cx| {
6671 view.move_line_up(&MoveLineUp, cx);
6672 assert_eq!(
6673 view.display_text(cx),
6674 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
6675 );
6676 assert_eq!(
6677 view.selected_display_ranges(cx),
6678 vec![
6679 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6680 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6681 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
6682 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
6683 ]
6684 );
6685 });
6686 }
6687
6688 #[gpui::test]
6689 fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
6690 let settings = EditorSettings::test(&cx);
6691 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
6692 let snapshot = buffer.read(cx).snapshot(cx);
6693 let (_, editor) =
6694 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6695 editor.update(cx, |editor, cx| {
6696 editor.insert_blocks(
6697 [BlockProperties {
6698 position: snapshot.anchor_after(Point::new(2, 0)),
6699 disposition: BlockDisposition::Below,
6700 height: 1,
6701 render: Arc::new(|_| Empty::new().boxed()),
6702 }],
6703 cx,
6704 );
6705 editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
6706 editor.move_line_down(&MoveLineDown, cx);
6707 });
6708 }
6709
6710 #[gpui::test]
6711 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
6712 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
6713 let settings = EditorSettings::test(&cx);
6714 let view = cx
6715 .add_window(Default::default(), |cx| {
6716 build_editor(buffer.clone(), settings, cx)
6717 })
6718 .1;
6719
6720 // Cut with three selections. Clipboard text is divided into three slices.
6721 view.update(cx, |view, cx| {
6722 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
6723 view.cut(&Cut, cx);
6724 assert_eq!(view.display_text(cx), "two four six ");
6725 });
6726
6727 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
6728 view.update(cx, |view, cx| {
6729 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
6730 view.paste(&Paste, cx);
6731 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
6732 assert_eq!(
6733 view.selected_display_ranges(cx),
6734 &[
6735 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6736 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
6737 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
6738 ]
6739 );
6740 });
6741
6742 // Paste again but with only two cursors. Since the number of cursors doesn't
6743 // match the number of slices in the clipboard, the entire clipboard text
6744 // is pasted at each cursor.
6745 view.update(cx, |view, cx| {
6746 view.select_ranges(vec![0..0, 31..31], None, cx);
6747 view.handle_input(&Input("( ".into()), cx);
6748 view.paste(&Paste, cx);
6749 view.handle_input(&Input(") ".into()), cx);
6750 assert_eq!(
6751 view.display_text(cx),
6752 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
6753 );
6754 });
6755
6756 view.update(cx, |view, cx| {
6757 view.select_ranges(vec![0..0], None, cx);
6758 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
6759 assert_eq!(
6760 view.display_text(cx),
6761 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
6762 );
6763 });
6764
6765 // Cut with three selections, one of which is full-line.
6766 view.update(cx, |view, cx| {
6767 view.select_display_ranges(
6768 &[
6769 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
6770 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6771 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
6772 ],
6773 cx,
6774 );
6775 view.cut(&Cut, cx);
6776 assert_eq!(
6777 view.display_text(cx),
6778 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
6779 );
6780 });
6781
6782 // Paste with three selections, noticing how the copied selection that was full-line
6783 // gets inserted before the second cursor.
6784 view.update(cx, |view, cx| {
6785 view.select_display_ranges(
6786 &[
6787 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6788 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6789 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
6790 ],
6791 cx,
6792 );
6793 view.paste(&Paste, cx);
6794 assert_eq!(
6795 view.display_text(cx),
6796 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
6797 );
6798 assert_eq!(
6799 view.selected_display_ranges(cx),
6800 &[
6801 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6802 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6803 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
6804 ]
6805 );
6806 });
6807
6808 // Copy with a single cursor only, which writes the whole line into the clipboard.
6809 view.update(cx, |view, cx| {
6810 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
6811 view.copy(&Copy, cx);
6812 });
6813
6814 // Paste with three selections, noticing how the copied full-line selection is inserted
6815 // before the empty selections but replaces the selection that is non-empty.
6816 view.update(cx, |view, cx| {
6817 view.select_display_ranges(
6818 &[
6819 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6820 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
6821 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6822 ],
6823 cx,
6824 );
6825 view.paste(&Paste, cx);
6826 assert_eq!(
6827 view.display_text(cx),
6828 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
6829 );
6830 assert_eq!(
6831 view.selected_display_ranges(cx),
6832 &[
6833 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6834 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6835 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
6836 ]
6837 );
6838 });
6839 }
6840
6841 #[gpui::test]
6842 fn test_select_all(cx: &mut gpui::MutableAppContext) {
6843 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
6844 let settings = EditorSettings::test(&cx);
6845 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6846 view.update(cx, |view, cx| {
6847 view.select_all(&SelectAll, cx);
6848 assert_eq!(
6849 view.selected_display_ranges(cx),
6850 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
6851 );
6852 });
6853 }
6854
6855 #[gpui::test]
6856 fn test_select_line(cx: &mut gpui::MutableAppContext) {
6857 let settings = EditorSettings::test(&cx);
6858 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
6859 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6860 view.update(cx, |view, cx| {
6861 view.select_display_ranges(
6862 &[
6863 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6864 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6865 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6866 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
6867 ],
6868 cx,
6869 );
6870 view.select_line(&SelectLine, cx);
6871 assert_eq!(
6872 view.selected_display_ranges(cx),
6873 vec![
6874 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
6875 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
6876 ]
6877 );
6878 });
6879
6880 view.update(cx, |view, cx| {
6881 view.select_line(&SelectLine, cx);
6882 assert_eq!(
6883 view.selected_display_ranges(cx),
6884 vec![
6885 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
6886 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
6887 ]
6888 );
6889 });
6890
6891 view.update(cx, |view, cx| {
6892 view.select_line(&SelectLine, cx);
6893 assert_eq!(
6894 view.selected_display_ranges(cx),
6895 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
6896 );
6897 });
6898 }
6899
6900 #[gpui::test]
6901 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
6902 let settings = EditorSettings::test(&cx);
6903 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
6904 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6905 view.update(cx, |view, cx| {
6906 view.fold_ranges(
6907 vec![
6908 Point::new(0, 2)..Point::new(1, 2),
6909 Point::new(2, 3)..Point::new(4, 1),
6910 Point::new(7, 0)..Point::new(8, 4),
6911 ],
6912 cx,
6913 );
6914 view.select_display_ranges(
6915 &[
6916 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6917 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6918 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6919 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6920 ],
6921 cx,
6922 );
6923 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
6924 });
6925
6926 view.update(cx, |view, cx| {
6927 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
6928 assert_eq!(
6929 view.display_text(cx),
6930 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
6931 );
6932 assert_eq!(
6933 view.selected_display_ranges(cx),
6934 [
6935 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6936 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6937 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6938 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
6939 ]
6940 );
6941 });
6942
6943 view.update(cx, |view, cx| {
6944 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
6945 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
6946 assert_eq!(
6947 view.display_text(cx),
6948 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
6949 );
6950 assert_eq!(
6951 view.selected_display_ranges(cx),
6952 [
6953 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
6954 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6955 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6956 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
6957 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
6958 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
6959 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
6960 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
6961 ]
6962 );
6963 });
6964 }
6965
6966 #[gpui::test]
6967 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
6968 let settings = EditorSettings::test(&cx);
6969 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
6970 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6971
6972 view.update(cx, |view, cx| {
6973 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
6974 });
6975 view.update(cx, |view, cx| {
6976 view.add_selection_above(&AddSelectionAbove, cx);
6977 assert_eq!(
6978 view.selected_display_ranges(cx),
6979 vec![
6980 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6981 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
6982 ]
6983 );
6984 });
6985
6986 view.update(cx, |view, cx| {
6987 view.add_selection_above(&AddSelectionAbove, cx);
6988 assert_eq!(
6989 view.selected_display_ranges(cx),
6990 vec![
6991 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6992 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
6993 ]
6994 );
6995 });
6996
6997 view.update(cx, |view, cx| {
6998 view.add_selection_below(&AddSelectionBelow, cx);
6999 assert_eq!(
7000 view.selected_display_ranges(cx),
7001 vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7002 );
7003 });
7004
7005 view.update(cx, |view, cx| {
7006 view.add_selection_below(&AddSelectionBelow, cx);
7007 assert_eq!(
7008 view.selected_display_ranges(cx),
7009 vec![
7010 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7011 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7012 ]
7013 );
7014 });
7015
7016 view.update(cx, |view, cx| {
7017 view.add_selection_below(&AddSelectionBelow, cx);
7018 assert_eq!(
7019 view.selected_display_ranges(cx),
7020 vec![
7021 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7022 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7023 ]
7024 );
7025 });
7026
7027 view.update(cx, |view, cx| {
7028 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
7029 });
7030 view.update(cx, |view, cx| {
7031 view.add_selection_below(&AddSelectionBelow, cx);
7032 assert_eq!(
7033 view.selected_display_ranges(cx),
7034 vec![
7035 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7036 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7037 ]
7038 );
7039 });
7040
7041 view.update(cx, |view, cx| {
7042 view.add_selection_below(&AddSelectionBelow, cx);
7043 assert_eq!(
7044 view.selected_display_ranges(cx),
7045 vec![
7046 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7047 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7048 ]
7049 );
7050 });
7051
7052 view.update(cx, |view, cx| {
7053 view.add_selection_above(&AddSelectionAbove, cx);
7054 assert_eq!(
7055 view.selected_display_ranges(cx),
7056 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7057 );
7058 });
7059
7060 view.update(cx, |view, cx| {
7061 view.add_selection_above(&AddSelectionAbove, cx);
7062 assert_eq!(
7063 view.selected_display_ranges(cx),
7064 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7065 );
7066 });
7067
7068 view.update(cx, |view, cx| {
7069 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
7070 view.add_selection_below(&AddSelectionBelow, cx);
7071 assert_eq!(
7072 view.selected_display_ranges(cx),
7073 vec![
7074 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7075 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7076 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7077 ]
7078 );
7079 });
7080
7081 view.update(cx, |view, cx| {
7082 view.add_selection_below(&AddSelectionBelow, cx);
7083 assert_eq!(
7084 view.selected_display_ranges(cx),
7085 vec![
7086 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7087 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7088 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7089 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
7090 ]
7091 );
7092 });
7093
7094 view.update(cx, |view, cx| {
7095 view.add_selection_above(&AddSelectionAbove, cx);
7096 assert_eq!(
7097 view.selected_display_ranges(cx),
7098 vec![
7099 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7100 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7101 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7102 ]
7103 );
7104 });
7105
7106 view.update(cx, |view, cx| {
7107 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
7108 });
7109 view.update(cx, |view, cx| {
7110 view.add_selection_above(&AddSelectionAbove, cx);
7111 assert_eq!(
7112 view.selected_display_ranges(cx),
7113 vec![
7114 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
7115 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7116 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7117 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7118 ]
7119 );
7120 });
7121
7122 view.update(cx, |view, cx| {
7123 view.add_selection_below(&AddSelectionBelow, cx);
7124 assert_eq!(
7125 view.selected_display_ranges(cx),
7126 vec![
7127 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7128 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7129 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7130 ]
7131 );
7132 });
7133 }
7134
7135 #[gpui::test]
7136 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
7137 let settings = cx.read(EditorSettings::test);
7138 let language = Arc::new(Language::new(
7139 LanguageConfig::default(),
7140 Some(tree_sitter_rust::language()),
7141 ));
7142
7143 let text = r#"
7144 use mod1::mod2::{mod3, mod4};
7145
7146 fn fn_1(param1: bool, param2: &str) {
7147 let var1 = "text";
7148 }
7149 "#
7150 .unindent();
7151
7152 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7153 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7154 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7155 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7156 .await;
7157
7158 view.update(&mut cx, |view, cx| {
7159 view.select_display_ranges(
7160 &[
7161 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7162 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7163 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7164 ],
7165 cx,
7166 );
7167 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7168 });
7169 assert_eq!(
7170 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7171 &[
7172 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7173 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7174 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7175 ]
7176 );
7177
7178 view.update(&mut cx, |view, cx| {
7179 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7180 });
7181 assert_eq!(
7182 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7183 &[
7184 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7185 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7186 ]
7187 );
7188
7189 view.update(&mut cx, |view, cx| {
7190 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7191 });
7192 assert_eq!(
7193 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7194 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7195 );
7196
7197 // Trying to expand the selected syntax node one more time has no effect.
7198 view.update(&mut cx, |view, cx| {
7199 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7200 });
7201 assert_eq!(
7202 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7203 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7204 );
7205
7206 view.update(&mut cx, |view, cx| {
7207 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7208 });
7209 assert_eq!(
7210 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7211 &[
7212 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7213 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7214 ]
7215 );
7216
7217 view.update(&mut cx, |view, cx| {
7218 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7219 });
7220 assert_eq!(
7221 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7222 &[
7223 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7224 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7225 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7226 ]
7227 );
7228
7229 view.update(&mut cx, |view, cx| {
7230 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7231 });
7232 assert_eq!(
7233 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7234 &[
7235 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7236 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7237 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7238 ]
7239 );
7240
7241 // Trying to shrink the selected syntax node one more time has no effect.
7242 view.update(&mut cx, |view, cx| {
7243 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7244 });
7245 assert_eq!(
7246 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7247 &[
7248 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7249 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7250 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7251 ]
7252 );
7253
7254 // Ensure that we keep expanding the selection if the larger selection starts or ends within
7255 // a fold.
7256 view.update(&mut cx, |view, cx| {
7257 view.fold_ranges(
7258 vec![
7259 Point::new(0, 21)..Point::new(0, 24),
7260 Point::new(3, 20)..Point::new(3, 22),
7261 ],
7262 cx,
7263 );
7264 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7265 });
7266 assert_eq!(
7267 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7268 &[
7269 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7270 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7271 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
7272 ]
7273 );
7274 }
7275
7276 #[gpui::test]
7277 async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
7278 let settings = cx.read(EditorSettings::test);
7279 let language = Arc::new(
7280 Language::new(
7281 LanguageConfig {
7282 brackets: vec![
7283 BracketPair {
7284 start: "{".to_string(),
7285 end: "}".to_string(),
7286 close: false,
7287 newline: true,
7288 },
7289 BracketPair {
7290 start: "(".to_string(),
7291 end: ")".to_string(),
7292 close: false,
7293 newline: true,
7294 },
7295 ],
7296 ..Default::default()
7297 },
7298 Some(tree_sitter_rust::language()),
7299 )
7300 .with_indents_query(
7301 r#"
7302 (_ "(" ")" @end) @indent
7303 (_ "{" "}" @end) @indent
7304 "#,
7305 )
7306 .unwrap(),
7307 );
7308
7309 let text = "fn a() {}";
7310
7311 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7312 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7313 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7314 editor
7315 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
7316 .await;
7317
7318 editor.update(&mut cx, |editor, cx| {
7319 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
7320 editor.newline(&Newline, cx);
7321 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
7322 assert_eq!(
7323 editor.selected_ranges(cx),
7324 &[
7325 Point::new(1, 4)..Point::new(1, 4),
7326 Point::new(3, 4)..Point::new(3, 4),
7327 Point::new(5, 0)..Point::new(5, 0)
7328 ]
7329 );
7330 });
7331 }
7332
7333 #[gpui::test]
7334 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
7335 let settings = cx.read(EditorSettings::test);
7336 let language = Arc::new(Language::new(
7337 LanguageConfig {
7338 brackets: vec![
7339 BracketPair {
7340 start: "{".to_string(),
7341 end: "}".to_string(),
7342 close: true,
7343 newline: true,
7344 },
7345 BracketPair {
7346 start: "/*".to_string(),
7347 end: " */".to_string(),
7348 close: true,
7349 newline: true,
7350 },
7351 ],
7352 ..Default::default()
7353 },
7354 Some(tree_sitter_rust::language()),
7355 ));
7356
7357 let text = r#"
7358 a
7359
7360 /
7361
7362 "#
7363 .unindent();
7364
7365 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7366 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7367 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7368 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7369 .await;
7370
7371 view.update(&mut cx, |view, cx| {
7372 view.select_display_ranges(
7373 &[
7374 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7375 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7376 ],
7377 cx,
7378 );
7379 view.handle_input(&Input("{".to_string()), cx);
7380 view.handle_input(&Input("{".to_string()), cx);
7381 view.handle_input(&Input("{".to_string()), cx);
7382 assert_eq!(
7383 view.text(cx),
7384 "
7385 {{{}}}
7386 {{{}}}
7387 /
7388
7389 "
7390 .unindent()
7391 );
7392
7393 view.move_right(&MoveRight, cx);
7394 view.handle_input(&Input("}".to_string()), cx);
7395 view.handle_input(&Input("}".to_string()), cx);
7396 view.handle_input(&Input("}".to_string()), cx);
7397 assert_eq!(
7398 view.text(cx),
7399 "
7400 {{{}}}}
7401 {{{}}}}
7402 /
7403
7404 "
7405 .unindent()
7406 );
7407
7408 view.undo(&Undo, cx);
7409 view.handle_input(&Input("/".to_string()), cx);
7410 view.handle_input(&Input("*".to_string()), cx);
7411 assert_eq!(
7412 view.text(cx),
7413 "
7414 /* */
7415 /* */
7416 /
7417
7418 "
7419 .unindent()
7420 );
7421
7422 view.undo(&Undo, cx);
7423 view.select_display_ranges(
7424 &[
7425 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7426 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7427 ],
7428 cx,
7429 );
7430 view.handle_input(&Input("*".to_string()), cx);
7431 assert_eq!(
7432 view.text(cx),
7433 "
7434 a
7435
7436 /*
7437 *
7438 "
7439 .unindent()
7440 );
7441 });
7442 }
7443
7444 #[gpui::test]
7445 async fn test_snippets(mut cx: gpui::TestAppContext) {
7446 let settings = cx.read(EditorSettings::test);
7447
7448 let text = "
7449 a. b
7450 a. b
7451 a. b
7452 "
7453 .unindent();
7454 let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
7455 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7456
7457 editor.update(&mut cx, |editor, cx| {
7458 let buffer = &editor.snapshot(cx).buffer_snapshot;
7459 let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
7460 let insertion_ranges = [
7461 Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
7462 Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
7463 Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
7464 ];
7465
7466 editor
7467 .insert_snippet(&insertion_ranges, snippet, cx)
7468 .unwrap();
7469 assert_eq!(
7470 editor.text(cx),
7471 "
7472 a.f(one, two, three) b
7473 a.f(one, two, three) b
7474 a.f(one, two, three) b
7475 "
7476 .unindent()
7477 );
7478 assert_eq!(
7479 editor.selected_ranges::<Point>(cx),
7480 &[
7481 Point::new(0, 4)..Point::new(0, 7),
7482 Point::new(0, 14)..Point::new(0, 19),
7483 Point::new(1, 4)..Point::new(1, 7),
7484 Point::new(1, 14)..Point::new(1, 19),
7485 Point::new(2, 4)..Point::new(2, 7),
7486 Point::new(2, 14)..Point::new(2, 19),
7487 ]
7488 );
7489
7490 // Can't move earlier than the first tab stop
7491 editor.move_to_prev_snippet_tabstop(cx);
7492 assert_eq!(
7493 editor.selected_ranges::<Point>(cx),
7494 &[
7495 Point::new(0, 4)..Point::new(0, 7),
7496 Point::new(0, 14)..Point::new(0, 19),
7497 Point::new(1, 4)..Point::new(1, 7),
7498 Point::new(1, 14)..Point::new(1, 19),
7499 Point::new(2, 4)..Point::new(2, 7),
7500 Point::new(2, 14)..Point::new(2, 19),
7501 ]
7502 );
7503
7504 assert!(editor.move_to_next_snippet_tabstop(cx));
7505 assert_eq!(
7506 editor.selected_ranges::<Point>(cx),
7507 &[
7508 Point::new(0, 9)..Point::new(0, 12),
7509 Point::new(1, 9)..Point::new(1, 12),
7510 Point::new(2, 9)..Point::new(2, 12)
7511 ]
7512 );
7513
7514 editor.move_to_prev_snippet_tabstop(cx);
7515 assert_eq!(
7516 editor.selected_ranges::<Point>(cx),
7517 &[
7518 Point::new(0, 4)..Point::new(0, 7),
7519 Point::new(0, 14)..Point::new(0, 19),
7520 Point::new(1, 4)..Point::new(1, 7),
7521 Point::new(1, 14)..Point::new(1, 19),
7522 Point::new(2, 4)..Point::new(2, 7),
7523 Point::new(2, 14)..Point::new(2, 19),
7524 ]
7525 );
7526
7527 assert!(editor.move_to_next_snippet_tabstop(cx));
7528 assert!(editor.move_to_next_snippet_tabstop(cx));
7529 assert_eq!(
7530 editor.selected_ranges::<Point>(cx),
7531 &[
7532 Point::new(0, 20)..Point::new(0, 20),
7533 Point::new(1, 20)..Point::new(1, 20),
7534 Point::new(2, 20)..Point::new(2, 20)
7535 ]
7536 );
7537
7538 // As soon as the last tab stop is reached, snippet state is gone
7539 editor.move_to_prev_snippet_tabstop(cx);
7540 assert_eq!(
7541 editor.selected_ranges::<Point>(cx),
7542 &[
7543 Point::new(0, 20)..Point::new(0, 20),
7544 Point::new(1, 20)..Point::new(1, 20),
7545 Point::new(2, 20)..Point::new(2, 20)
7546 ]
7547 );
7548 });
7549 }
7550
7551 #[gpui::test]
7552 async fn test_completion(mut cx: gpui::TestAppContext) {
7553 let settings = cx.read(EditorSettings::test);
7554 let (language_server, mut fake) = lsp::LanguageServer::fake_with_capabilities(
7555 lsp::ServerCapabilities {
7556 completion_provider: Some(lsp::CompletionOptions {
7557 trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
7558 ..Default::default()
7559 }),
7560 ..Default::default()
7561 },
7562 &cx,
7563 )
7564 .await;
7565
7566 let text = "
7567 one
7568 two
7569 three
7570 "
7571 .unindent();
7572
7573 let fs = Arc::new(FakeFs::new(cx.background().clone()));
7574 fs.insert_file("/file", text).await.unwrap();
7575
7576 let project = Project::test(fs, &mut cx);
7577
7578 let (worktree, relative_path) = project
7579 .update(&mut cx, |project, cx| {
7580 project.find_or_create_local_worktree("/file", false, cx)
7581 })
7582 .await
7583 .unwrap();
7584 let project_path = ProjectPath {
7585 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
7586 path: relative_path.into(),
7587 };
7588 let buffer = project
7589 .update(&mut cx, |project, cx| project.open_buffer(project_path, cx))
7590 .await
7591 .unwrap();
7592 buffer.update(&mut cx, |buffer, cx| {
7593 buffer.set_language_server(Some(language_server), cx);
7594 });
7595
7596 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7597 buffer.next_notification(&cx).await;
7598
7599 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7600
7601 editor.update(&mut cx, |editor, cx| {
7602 editor.project = Some(project);
7603 editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
7604 editor.handle_input(&Input(".".to_string()), cx);
7605 });
7606
7607 handle_completion_request(
7608 &mut fake,
7609 "/file",
7610 Point::new(0, 4),
7611 &[
7612 (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
7613 (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
7614 ],
7615 )
7616 .await;
7617 editor.next_notification(&cx).await;
7618
7619 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
7620 editor.move_down(&MoveDown, cx);
7621 let apply_additional_edits = editor
7622 .confirm_completion(&ConfirmCompletion(None), cx)
7623 .unwrap();
7624 assert_eq!(
7625 editor.text(cx),
7626 "
7627 one.second_completion
7628 two
7629 three
7630 "
7631 .unindent()
7632 );
7633 apply_additional_edits
7634 });
7635
7636 handle_resolve_completion_request(
7637 &mut fake,
7638 Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
7639 )
7640 .await;
7641 apply_additional_edits.await.unwrap();
7642 assert_eq!(
7643 editor.read_with(&cx, |editor, cx| editor.text(cx)),
7644 "
7645 one.second_completion
7646 two
7647 three
7648 additional edit
7649 "
7650 .unindent()
7651 );
7652
7653 editor.update(&mut cx, |editor, cx| {
7654 editor.select_ranges(
7655 [
7656 Point::new(1, 3)..Point::new(1, 3),
7657 Point::new(2, 5)..Point::new(2, 5),
7658 ],
7659 None,
7660 cx,
7661 );
7662
7663 editor.handle_input(&Input(" ".to_string()), cx);
7664 assert!(editor.context_menu.is_none());
7665 editor.handle_input(&Input("s".to_string()), cx);
7666 assert!(editor.context_menu.is_none());
7667 });
7668
7669 handle_completion_request(
7670 &mut fake,
7671 "/file",
7672 Point::new(2, 7),
7673 &[
7674 (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
7675 (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
7676 (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
7677 ],
7678 )
7679 .await;
7680 editor
7681 .condition(&cx, |editor, _| editor.context_menu.is_some())
7682 .await;
7683
7684 editor.update(&mut cx, |editor, cx| {
7685 editor.handle_input(&Input("i".to_string()), cx);
7686 });
7687
7688 handle_completion_request(
7689 &mut fake,
7690 "/file",
7691 Point::new(2, 8),
7692 &[
7693 (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
7694 (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
7695 (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
7696 ],
7697 )
7698 .await;
7699 editor.next_notification(&cx).await;
7700
7701 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
7702 let apply_additional_edits = editor
7703 .confirm_completion(&ConfirmCompletion(None), cx)
7704 .unwrap();
7705 assert_eq!(
7706 editor.text(cx),
7707 "
7708 one.second_completion
7709 two sixth_completion
7710 three sixth_completion
7711 additional edit
7712 "
7713 .unindent()
7714 );
7715 apply_additional_edits
7716 });
7717 handle_resolve_completion_request(&mut fake, None).await;
7718 apply_additional_edits.await.unwrap();
7719
7720 async fn handle_completion_request(
7721 fake: &mut FakeLanguageServer,
7722 path: &str,
7723 position: Point,
7724 completions: &[(Range<Point>, &str)],
7725 ) {
7726 let (id, params) = fake.receive_request::<lsp::request::Completion>().await;
7727 assert_eq!(
7728 params.text_document_position.text_document.uri,
7729 lsp::Url::from_file_path(path).unwrap()
7730 );
7731 assert_eq!(
7732 params.text_document_position.position,
7733 lsp::Position::new(position.row, position.column)
7734 );
7735
7736 let completions = completions
7737 .iter()
7738 .map(|(range, new_text)| lsp::CompletionItem {
7739 label: new_text.to_string(),
7740 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
7741 range: lsp::Range::new(
7742 lsp::Position::new(range.start.row, range.start.column),
7743 lsp::Position::new(range.start.row, range.start.column),
7744 ),
7745 new_text: new_text.to_string(),
7746 })),
7747 ..Default::default()
7748 })
7749 .collect();
7750 fake.respond(id, Some(lsp::CompletionResponse::Array(completions)))
7751 .await;
7752 }
7753
7754 async fn handle_resolve_completion_request(
7755 fake: &mut FakeLanguageServer,
7756 edit: Option<(Range<Point>, &str)>,
7757 ) {
7758 let (id, _) = fake
7759 .receive_request::<lsp::request::ResolveCompletionItem>()
7760 .await;
7761 fake.respond(
7762 id,
7763 lsp::CompletionItem {
7764 additional_text_edits: edit.map(|(range, new_text)| {
7765 vec![lsp::TextEdit::new(
7766 lsp::Range::new(
7767 lsp::Position::new(range.start.row, range.start.column),
7768 lsp::Position::new(range.end.row, range.end.column),
7769 ),
7770 new_text.to_string(),
7771 )]
7772 }),
7773 ..Default::default()
7774 },
7775 )
7776 .await;
7777 }
7778 }
7779
7780 #[gpui::test]
7781 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
7782 let settings = cx.read(EditorSettings::test);
7783 let language = Arc::new(Language::new(
7784 LanguageConfig {
7785 line_comment: Some("// ".to_string()),
7786 ..Default::default()
7787 },
7788 Some(tree_sitter_rust::language()),
7789 ));
7790
7791 let text = "
7792 fn a() {
7793 //b();
7794 // c();
7795 // d();
7796 }
7797 "
7798 .unindent();
7799
7800 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7801 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7802 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7803
7804 view.update(&mut cx, |editor, cx| {
7805 // If multiple selections intersect a line, the line is only
7806 // toggled once.
7807 editor.select_display_ranges(
7808 &[
7809 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
7810 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
7811 ],
7812 cx,
7813 );
7814 editor.toggle_comments(&ToggleComments, cx);
7815 assert_eq!(
7816 editor.text(cx),
7817 "
7818 fn a() {
7819 b();
7820 c();
7821 d();
7822 }
7823 "
7824 .unindent()
7825 );
7826
7827 // The comment prefix is inserted at the same column for every line
7828 // in a selection.
7829 editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
7830 editor.toggle_comments(&ToggleComments, cx);
7831 assert_eq!(
7832 editor.text(cx),
7833 "
7834 fn a() {
7835 // b();
7836 // c();
7837 // d();
7838 }
7839 "
7840 .unindent()
7841 );
7842
7843 // If a selection ends at the beginning of a line, that line is not toggled.
7844 editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
7845 editor.toggle_comments(&ToggleComments, cx);
7846 assert_eq!(
7847 editor.text(cx),
7848 "
7849 fn a() {
7850 // b();
7851 c();
7852 // d();
7853 }
7854 "
7855 .unindent()
7856 );
7857 });
7858 }
7859
7860 #[gpui::test]
7861 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
7862 let settings = EditorSettings::test(cx);
7863 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
7864 let multibuffer = cx.add_model(|cx| {
7865 let mut multibuffer = MultiBuffer::new(0);
7866 multibuffer.push_excerpt(
7867 ExcerptProperties {
7868 buffer: &buffer,
7869 range: Point::new(0, 0)..Point::new(0, 4),
7870 },
7871 cx,
7872 );
7873 multibuffer.push_excerpt(
7874 ExcerptProperties {
7875 buffer: &buffer,
7876 range: Point::new(1, 0)..Point::new(1, 4),
7877 },
7878 cx,
7879 );
7880 multibuffer
7881 });
7882
7883 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
7884
7885 let (_, view) = cx.add_window(Default::default(), |cx| {
7886 build_editor(multibuffer, settings, cx)
7887 });
7888 view.update(cx, |view, cx| {
7889 view.select_display_ranges(
7890 &[
7891 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7892 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7893 ],
7894 cx,
7895 );
7896
7897 view.handle_input(&Input("X".to_string()), cx);
7898 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
7899 assert_eq!(
7900 view.selected_display_ranges(cx),
7901 &[
7902 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7903 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7904 ]
7905 )
7906 });
7907 }
7908
7909 #[gpui::test]
7910 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
7911 let settings = EditorSettings::test(cx);
7912 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
7913 let multibuffer = cx.add_model(|cx| {
7914 let mut multibuffer = MultiBuffer::new(0);
7915 multibuffer.push_excerpt(
7916 ExcerptProperties {
7917 buffer: &buffer,
7918 range: Point::new(0, 0)..Point::new(1, 4),
7919 },
7920 cx,
7921 );
7922 multibuffer.push_excerpt(
7923 ExcerptProperties {
7924 buffer: &buffer,
7925 range: Point::new(1, 0)..Point::new(2, 4),
7926 },
7927 cx,
7928 );
7929 multibuffer
7930 });
7931
7932 assert_eq!(
7933 multibuffer.read(cx).read(cx).text(),
7934 "aaaa\nbbbb\nbbbb\ncccc"
7935 );
7936
7937 let (_, view) = cx.add_window(Default::default(), |cx| {
7938 build_editor(multibuffer, settings, cx)
7939 });
7940 view.update(cx, |view, cx| {
7941 view.select_display_ranges(
7942 &[
7943 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7944 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
7945 ],
7946 cx,
7947 );
7948
7949 view.handle_input(&Input("X".to_string()), cx);
7950 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
7951 assert_eq!(
7952 view.selected_display_ranges(cx),
7953 &[
7954 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7955 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7956 ]
7957 );
7958
7959 view.newline(&Newline, cx);
7960 assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
7961 assert_eq!(
7962 view.selected_display_ranges(cx),
7963 &[
7964 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7965 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7966 ]
7967 );
7968 });
7969 }
7970
7971 #[gpui::test]
7972 fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
7973 let settings = EditorSettings::test(cx);
7974 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
7975 let mut excerpt1_id = None;
7976 let multibuffer = cx.add_model(|cx| {
7977 let mut multibuffer = MultiBuffer::new(0);
7978 excerpt1_id = Some(multibuffer.push_excerpt(
7979 ExcerptProperties {
7980 buffer: &buffer,
7981 range: Point::new(0, 0)..Point::new(1, 4),
7982 },
7983 cx,
7984 ));
7985 multibuffer.push_excerpt(
7986 ExcerptProperties {
7987 buffer: &buffer,
7988 range: Point::new(1, 0)..Point::new(2, 4),
7989 },
7990 cx,
7991 );
7992 multibuffer
7993 });
7994 assert_eq!(
7995 multibuffer.read(cx).read(cx).text(),
7996 "aaaa\nbbbb\nbbbb\ncccc"
7997 );
7998 let (_, editor) = cx.add_window(Default::default(), |cx| {
7999 let mut editor = build_editor(multibuffer.clone(), settings, cx);
8000 editor.select_display_ranges(
8001 &[
8002 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
8003 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8004 ],
8005 cx,
8006 );
8007 editor
8008 });
8009
8010 // Refreshing selections is a no-op when excerpts haven't changed.
8011 editor.update(cx, |editor, cx| {
8012 editor.refresh_selections(cx);
8013 assert_eq!(
8014 editor.selected_display_ranges(cx),
8015 [
8016 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
8017 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8018 ]
8019 );
8020 });
8021
8022 multibuffer.update(cx, |multibuffer, cx| {
8023 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
8024 });
8025 editor.update(cx, |editor, cx| {
8026 // Removing an excerpt causes the first selection to become degenerate.
8027 assert_eq!(
8028 editor.selected_display_ranges(cx),
8029 [
8030 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
8031 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
8032 ]
8033 );
8034
8035 // Refreshing selections will relocate the first selection to the original buffer
8036 // location.
8037 editor.refresh_selections(cx);
8038 assert_eq!(
8039 editor.selected_display_ranges(cx),
8040 [
8041 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
8042 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3)
8043 ]
8044 );
8045 });
8046 }
8047
8048 #[gpui::test]
8049 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
8050 let settings = cx.read(EditorSettings::test);
8051 let language = Arc::new(Language::new(
8052 LanguageConfig {
8053 brackets: vec![
8054 BracketPair {
8055 start: "{".to_string(),
8056 end: "}".to_string(),
8057 close: true,
8058 newline: true,
8059 },
8060 BracketPair {
8061 start: "/* ".to_string(),
8062 end: " */".to_string(),
8063 close: true,
8064 newline: true,
8065 },
8066 ],
8067 ..Default::default()
8068 },
8069 Some(tree_sitter_rust::language()),
8070 ));
8071
8072 let text = concat!(
8073 "{ }\n", // Suppress rustfmt
8074 " x\n", //
8075 " /* */\n", //
8076 "x\n", //
8077 "{{} }\n", //
8078 );
8079
8080 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8081 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8082 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8083 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8084 .await;
8085
8086 view.update(&mut cx, |view, cx| {
8087 view.select_display_ranges(
8088 &[
8089 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
8090 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
8091 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
8092 ],
8093 cx,
8094 );
8095 view.newline(&Newline, cx);
8096
8097 assert_eq!(
8098 view.buffer().read(cx).read(cx).text(),
8099 concat!(
8100 "{ \n", // Suppress rustfmt
8101 "\n", //
8102 "}\n", //
8103 " x\n", //
8104 " /* \n", //
8105 " \n", //
8106 " */\n", //
8107 "x\n", //
8108 "{{} \n", //
8109 "}\n", //
8110 )
8111 );
8112 });
8113 }
8114
8115 #[gpui::test]
8116 fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
8117 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
8118 let settings = EditorSettings::test(&cx);
8119 let (_, editor) = cx.add_window(Default::default(), |cx| {
8120 build_editor(buffer.clone(), settings, cx)
8121 });
8122
8123 editor.update(cx, |editor, cx| {
8124 struct Type1;
8125 struct Type2;
8126
8127 let buffer = buffer.read(cx).snapshot(cx);
8128
8129 let anchor_range = |range: Range<Point>| {
8130 buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
8131 };
8132
8133 editor.highlight_ranges::<Type1>(
8134 vec![
8135 anchor_range(Point::new(2, 1)..Point::new(2, 3)),
8136 anchor_range(Point::new(4, 2)..Point::new(4, 4)),
8137 anchor_range(Point::new(6, 3)..Point::new(6, 5)),
8138 anchor_range(Point::new(8, 4)..Point::new(8, 6)),
8139 ],
8140 Color::red(),
8141 cx,
8142 );
8143 editor.highlight_ranges::<Type2>(
8144 vec![
8145 anchor_range(Point::new(3, 2)..Point::new(3, 5)),
8146 anchor_range(Point::new(5, 3)..Point::new(5, 6)),
8147 anchor_range(Point::new(7, 4)..Point::new(7, 7)),
8148 anchor_range(Point::new(9, 5)..Point::new(9, 8)),
8149 ],
8150 Color::green(),
8151 cx,
8152 );
8153
8154 let snapshot = editor.snapshot(cx);
8155 let mut highlighted_ranges = editor.highlighted_ranges_in_range(
8156 anchor_range(Point::new(3, 4)..Point::new(7, 4)),
8157 &snapshot,
8158 );
8159 // Enforce a consistent ordering based on color without relying on the ordering of the
8160 // highlight's `TypeId` which is non-deterministic.
8161 highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
8162 assert_eq!(
8163 highlighted_ranges,
8164 &[
8165 (
8166 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
8167 Color::green(),
8168 ),
8169 (
8170 DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
8171 Color::green(),
8172 ),
8173 (
8174 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
8175 Color::red(),
8176 ),
8177 (
8178 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8179 Color::red(),
8180 ),
8181 ]
8182 );
8183 assert_eq!(
8184 editor.highlighted_ranges_in_range(
8185 anchor_range(Point::new(5, 6)..Point::new(6, 4)),
8186 &snapshot,
8187 ),
8188 &[(
8189 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8190 Color::red(),
8191 )]
8192 );
8193 });
8194 }
8195
8196 #[test]
8197 fn test_combine_syntax_and_fuzzy_match_highlights() {
8198 let string = "abcdefghijklmnop";
8199 let default = HighlightStyle::default();
8200 let syntax_ranges = [
8201 (
8202 0..3,
8203 HighlightStyle {
8204 color: Color::red(),
8205 ..default
8206 },
8207 ),
8208 (
8209 4..8,
8210 HighlightStyle {
8211 color: Color::green(),
8212 ..default
8213 },
8214 ),
8215 ];
8216 let match_indices = [4, 6, 7, 8];
8217 assert_eq!(
8218 combine_syntax_and_fuzzy_match_highlights(
8219 &string,
8220 default,
8221 syntax_ranges.into_iter(),
8222 &match_indices,
8223 ),
8224 &[
8225 (
8226 0..3,
8227 HighlightStyle {
8228 color: Color::red(),
8229 ..default
8230 },
8231 ),
8232 (
8233 4..5,
8234 HighlightStyle {
8235 color: Color::green(),
8236 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8237 ..default
8238 },
8239 ),
8240 (
8241 5..6,
8242 HighlightStyle {
8243 color: Color::green(),
8244 ..default
8245 },
8246 ),
8247 (
8248 6..8,
8249 HighlightStyle {
8250 color: Color::green(),
8251 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8252 ..default
8253 },
8254 ),
8255 (
8256 8..9,
8257 HighlightStyle {
8258 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8259 ..default
8260 },
8261 ),
8262 ]
8263 );
8264 }
8265
8266 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
8267 let point = DisplayPoint::new(row as u32, column as u32);
8268 point..point
8269 }
8270
8271 fn build_editor(
8272 buffer: ModelHandle<MultiBuffer>,
8273 settings: EditorSettings,
8274 cx: &mut ViewContext<Editor>,
8275 ) -> Editor {
8276 Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), None, cx)
8277 }
8278}
8279
8280trait RangeExt<T> {
8281 fn sorted(&self) -> Range<T>;
8282 fn to_inclusive(&self) -> RangeInclusive<T>;
8283}
8284
8285impl<T: Ord + Clone> RangeExt<T> for Range<T> {
8286 fn sorted(&self) -> Self {
8287 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
8288 }
8289
8290 fn to_inclusive(&self) -> RangeInclusive<T> {
8291 self.start.clone()..=self.end.clone()
8292 }
8293}