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