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