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