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