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