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