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