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