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