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