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