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