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