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