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