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