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 set_text(&mut self, text: impl Into<String>, cx: &mut ViewContext<Self>) {
5148 self.buffer
5149 .read(cx)
5150 .as_singleton()
5151 .expect("you can only call set_text on editors for singleton buffers")
5152 .update(cx, |buffer, cx| buffer.set_text(text, cx));
5153 }
5154
5155 pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
5156 self.display_map
5157 .update(cx, |map, cx| map.snapshot(cx))
5158 .text()
5159 }
5160
5161 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
5162 let language = self.language(cx);
5163 let settings = self.settings.borrow();
5164 let mode = self
5165 .soft_wrap_mode_override
5166 .unwrap_or_else(|| settings.soft_wrap(language));
5167 match mode {
5168 settings::SoftWrap::None => SoftWrap::None,
5169 settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
5170 settings::SoftWrap::PreferredLineLength => {
5171 SoftWrap::Column(settings.preferred_line_length(language))
5172 }
5173 }
5174 }
5175
5176 pub fn set_soft_wrap_mode(&mut self, mode: settings::SoftWrap, cx: &mut ViewContext<Self>) {
5177 self.soft_wrap_mode_override = Some(mode);
5178 cx.notify();
5179 }
5180
5181 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
5182 self.display_map
5183 .update(cx, |map, cx| map.set_wrap_width(width, cx))
5184 }
5185
5186 pub fn set_highlighted_rows(&mut self, rows: Option<Range<u32>>) {
5187 self.highlighted_rows = rows;
5188 }
5189
5190 pub fn highlighted_rows(&self) -> Option<Range<u32>> {
5191 self.highlighted_rows.clone()
5192 }
5193
5194 pub fn highlight_ranges<T: 'static>(
5195 &mut self,
5196 ranges: Vec<Range<Anchor>>,
5197 color: Color,
5198 cx: &mut ViewContext<Self>,
5199 ) {
5200 self.highlighted_ranges
5201 .insert(TypeId::of::<T>(), (color, ranges));
5202 cx.notify();
5203 }
5204
5205 pub fn clear_highlighted_ranges<T: 'static>(
5206 &mut self,
5207 cx: &mut ViewContext<Self>,
5208 ) -> Option<(Color, Vec<Range<Anchor>>)> {
5209 cx.notify();
5210 self.highlighted_ranges.remove(&TypeId::of::<T>())
5211 }
5212
5213 #[cfg(feature = "test-support")]
5214 pub fn all_highlighted_ranges(
5215 &mut self,
5216 cx: &mut ViewContext<Self>,
5217 ) -> Vec<(Range<DisplayPoint>, Color)> {
5218 let snapshot = self.snapshot(cx);
5219 let buffer = &snapshot.buffer_snapshot;
5220 let start = buffer.anchor_before(0);
5221 let end = buffer.anchor_after(buffer.len());
5222 self.highlighted_ranges_in_range(start..end, &snapshot)
5223 }
5224
5225 pub fn highlighted_ranges_for_type<T: 'static>(&self) -> Option<(Color, &[Range<Anchor>])> {
5226 self.highlighted_ranges
5227 .get(&TypeId::of::<T>())
5228 .map(|(color, ranges)| (*color, ranges.as_slice()))
5229 }
5230
5231 pub fn highlighted_ranges_in_range(
5232 &self,
5233 search_range: Range<Anchor>,
5234 display_snapshot: &DisplaySnapshot,
5235 ) -> Vec<(Range<DisplayPoint>, Color)> {
5236 let mut results = Vec::new();
5237 let buffer = &display_snapshot.buffer_snapshot;
5238 for (color, ranges) in self.highlighted_ranges.values() {
5239 let start_ix = match ranges.binary_search_by(|probe| {
5240 let cmp = probe.end.cmp(&search_range.start, &buffer).unwrap();
5241 if cmp.is_gt() {
5242 Ordering::Greater
5243 } else {
5244 Ordering::Less
5245 }
5246 }) {
5247 Ok(i) | Err(i) => i,
5248 };
5249 for range in &ranges[start_ix..] {
5250 if range.start.cmp(&search_range.end, &buffer).unwrap().is_ge() {
5251 break;
5252 }
5253 let start = range
5254 .start
5255 .to_point(buffer)
5256 .to_display_point(display_snapshot);
5257 let end = range
5258 .end
5259 .to_point(buffer)
5260 .to_display_point(display_snapshot);
5261 results.push((start..end, *color))
5262 }
5263 }
5264 results
5265 }
5266
5267 fn next_blink_epoch(&mut self) -> usize {
5268 self.blink_epoch += 1;
5269 self.blink_epoch
5270 }
5271
5272 fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
5273 if !self.focused {
5274 return;
5275 }
5276
5277 self.show_local_cursors = true;
5278 cx.notify();
5279
5280 let epoch = self.next_blink_epoch();
5281 cx.spawn(|this, mut cx| {
5282 let this = this.downgrade();
5283 async move {
5284 Timer::after(CURSOR_BLINK_INTERVAL).await;
5285 if let Some(this) = this.upgrade(&cx) {
5286 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
5287 }
5288 }
5289 })
5290 .detach();
5291 }
5292
5293 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5294 if epoch == self.blink_epoch {
5295 self.blinking_paused = false;
5296 self.blink_cursors(epoch, cx);
5297 }
5298 }
5299
5300 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
5301 if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
5302 self.show_local_cursors = !self.show_local_cursors;
5303 cx.notify();
5304
5305 let epoch = self.next_blink_epoch();
5306 cx.spawn(|this, mut cx| {
5307 let this = this.downgrade();
5308 async move {
5309 Timer::after(CURSOR_BLINK_INTERVAL).await;
5310 if let Some(this) = this.upgrade(&cx) {
5311 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
5312 }
5313 }
5314 })
5315 .detach();
5316 }
5317 }
5318
5319 pub fn show_local_cursors(&self) -> bool {
5320 self.show_local_cursors
5321 }
5322
5323 fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
5324 cx.notify();
5325 }
5326
5327 fn on_buffer_event(
5328 &mut self,
5329 _: ModelHandle<MultiBuffer>,
5330 event: &language::Event,
5331 cx: &mut ViewContext<Self>,
5332 ) {
5333 match event {
5334 language::Event::Edited => {
5335 self.refresh_active_diagnostics(cx);
5336 self.refresh_code_actions(cx);
5337 cx.emit(Event::Edited);
5338 }
5339 language::Event::Dirtied => cx.emit(Event::Dirtied),
5340 language::Event::Saved => cx.emit(Event::Saved),
5341 language::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
5342 language::Event::Reloaded => cx.emit(Event::TitleChanged),
5343 language::Event::Closed => cx.emit(Event::Closed),
5344 language::Event::DiagnosticsUpdated => {
5345 self.refresh_active_diagnostics(cx);
5346 }
5347 _ => {}
5348 }
5349 }
5350
5351 fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
5352 cx.notify();
5353 }
5354
5355 pub fn set_searchable(&mut self, searchable: bool) {
5356 self.searchable = searchable;
5357 }
5358
5359 pub fn searchable(&self) -> bool {
5360 self.searchable
5361 }
5362
5363 fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
5364 let active_item = workspace.active_item(cx);
5365 let editor_handle = if let Some(editor) = active_item
5366 .as_ref()
5367 .and_then(|item| item.act_as::<Self>(cx))
5368 {
5369 editor
5370 } else {
5371 cx.propagate_action();
5372 return;
5373 };
5374
5375 let editor = editor_handle.read(cx);
5376 let buffer = editor.buffer.read(cx);
5377 if buffer.is_singleton() {
5378 cx.propagate_action();
5379 return;
5380 }
5381
5382 let mut new_selections_by_buffer = HashMap::default();
5383 for selection in editor.local_selections::<usize>(cx) {
5384 for (buffer, mut range) in
5385 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
5386 {
5387 if selection.reversed {
5388 mem::swap(&mut range.start, &mut range.end);
5389 }
5390 new_selections_by_buffer
5391 .entry(buffer)
5392 .or_insert(Vec::new())
5393 .push(range)
5394 }
5395 }
5396
5397 editor_handle.update(cx, |editor, cx| {
5398 editor.push_to_nav_history(editor.newest_anchor_selection().head(), None, cx);
5399 });
5400 let nav_history = workspace.active_pane().read(cx).nav_history().clone();
5401 nav_history.borrow_mut().disable();
5402
5403 // We defer the pane interaction because we ourselves are a workspace item
5404 // and activating a new item causes the pane to call a method on us reentrantly,
5405 // which panics if we're on the stack.
5406 cx.defer(move |workspace, cx| {
5407 for (ix, (buffer, ranges)) in new_selections_by_buffer.into_iter().enumerate() {
5408 let buffer = BufferItemHandle(buffer);
5409 if ix == 0 && !workspace.activate_pane_for_item(&buffer, cx) {
5410 workspace.activate_next_pane(cx);
5411 }
5412
5413 let editor = workspace
5414 .open_item(buffer, cx)
5415 .downcast::<Editor>()
5416 .unwrap();
5417
5418 editor.update(cx, |editor, cx| {
5419 editor.select_ranges(ranges, Some(Autoscroll::Newest), cx);
5420 });
5421 }
5422
5423 nav_history.borrow_mut().enable();
5424 });
5425 }
5426}
5427
5428impl EditorSnapshot {
5429 pub fn is_focused(&self) -> bool {
5430 self.is_focused
5431 }
5432
5433 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
5434 self.placeholder_text.as_ref()
5435 }
5436
5437 pub fn scroll_position(&self) -> Vector2F {
5438 compute_scroll_position(
5439 &self.display_snapshot,
5440 self.scroll_position,
5441 &self.scroll_top_anchor,
5442 )
5443 }
5444}
5445
5446impl Deref for EditorSnapshot {
5447 type Target = DisplaySnapshot;
5448
5449 fn deref(&self) -> &Self::Target {
5450 &self.display_snapshot
5451 }
5452}
5453
5454fn compute_scroll_position(
5455 snapshot: &DisplaySnapshot,
5456 mut scroll_position: Vector2F,
5457 scroll_top_anchor: &Option<Anchor>,
5458) -> Vector2F {
5459 if let Some(anchor) = scroll_top_anchor {
5460 let scroll_top = anchor.to_display_point(snapshot).row() as f32;
5461 scroll_position.set_y(scroll_top + scroll_position.y());
5462 } else {
5463 scroll_position.set_y(0.);
5464 }
5465 scroll_position
5466}
5467
5468#[derive(Copy, Clone)]
5469pub enum Event {
5470 Activate,
5471 Edited,
5472 Blurred,
5473 Dirtied,
5474 Saved,
5475 TitleChanged,
5476 SelectionsChanged,
5477 Closed,
5478}
5479
5480impl Entity for Editor {
5481 type Event = Event;
5482}
5483
5484impl View for Editor {
5485 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
5486 let style = self.style(cx);
5487 self.display_map.update(cx, |map, cx| {
5488 map.set_font(style.text.font_id, style.text.font_size, cx)
5489 });
5490 EditorElement::new(self.handle.clone(), style.clone()).boxed()
5491 }
5492
5493 fn ui_name() -> &'static str {
5494 "Editor"
5495 }
5496
5497 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
5498 self.focused = true;
5499 self.blink_cursors(self.blink_epoch, cx);
5500 self.buffer.update(cx, |buffer, cx| {
5501 buffer.finalize_last_transaction(cx);
5502 buffer.set_active_selections(&self.selections, cx)
5503 });
5504 }
5505
5506 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
5507 self.focused = false;
5508 self.show_local_cursors = false;
5509 self.buffer
5510 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
5511 self.hide_context_menu(cx);
5512 cx.emit(Event::Blurred);
5513 cx.notify();
5514 }
5515
5516 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
5517 let mut cx = Self::default_keymap_context();
5518 let mode = match self.mode {
5519 EditorMode::SingleLine => "single_line",
5520 EditorMode::AutoHeight { .. } => "auto_height",
5521 EditorMode::Full => "full",
5522 };
5523 cx.map.insert("mode".into(), mode.into());
5524 if self.pending_rename.is_some() {
5525 cx.set.insert("renaming".into());
5526 }
5527 match self.context_menu.as_ref() {
5528 Some(ContextMenu::Completions(_)) => {
5529 cx.set.insert("showing_completions".into());
5530 }
5531 Some(ContextMenu::CodeActions(_)) => {
5532 cx.set.insert("showing_code_actions".into());
5533 }
5534 None => {}
5535 }
5536 cx
5537 }
5538}
5539
5540fn build_style(
5541 settings: &Settings,
5542 get_field_editor_theme: Option<GetFieldEditorTheme>,
5543 cx: &AppContext,
5544) -> EditorStyle {
5545 let mut theme = settings.theme.editor.clone();
5546 if let Some(get_field_editor_theme) = get_field_editor_theme {
5547 let field_editor_theme = get_field_editor_theme(&settings.theme);
5548 if let Some(background) = field_editor_theme.container.background_color {
5549 theme.background = background;
5550 }
5551 theme.text_color = field_editor_theme.text.color;
5552 theme.selection = field_editor_theme.selection;
5553 EditorStyle {
5554 text: field_editor_theme.text,
5555 placeholder_text: field_editor_theme.placeholder_text,
5556 theme,
5557 }
5558 } else {
5559 let font_cache = cx.font_cache();
5560 let font_family_id = settings.buffer_font_family;
5561 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
5562 let font_properties = Default::default();
5563 let font_id = font_cache
5564 .select_font(font_family_id, &font_properties)
5565 .unwrap();
5566 let font_size = settings.buffer_font_size;
5567 EditorStyle {
5568 text: TextStyle {
5569 color: settings.theme.editor.text_color,
5570 font_family_name,
5571 font_family_id,
5572 font_id,
5573 font_size,
5574 font_properties,
5575 underline: None,
5576 },
5577 placeholder_text: None,
5578 theme,
5579 }
5580 }
5581}
5582
5583impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
5584 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
5585 let start = self.start.to_point(buffer);
5586 let end = self.end.to_point(buffer);
5587 if self.reversed {
5588 end..start
5589 } else {
5590 start..end
5591 }
5592 }
5593
5594 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
5595 let start = self.start.to_offset(buffer);
5596 let end = self.end.to_offset(buffer);
5597 if self.reversed {
5598 end..start
5599 } else {
5600 start..end
5601 }
5602 }
5603
5604 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
5605 let start = self
5606 .start
5607 .to_point(&map.buffer_snapshot)
5608 .to_display_point(map);
5609 let end = self
5610 .end
5611 .to_point(&map.buffer_snapshot)
5612 .to_display_point(map);
5613 if self.reversed {
5614 end..start
5615 } else {
5616 start..end
5617 }
5618 }
5619
5620 fn spanned_rows(
5621 &self,
5622 include_end_if_at_line_start: bool,
5623 map: &DisplaySnapshot,
5624 ) -> Range<u32> {
5625 let start = self.start.to_point(&map.buffer_snapshot);
5626 let mut end = self.end.to_point(&map.buffer_snapshot);
5627 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
5628 end.row -= 1;
5629 }
5630
5631 let buffer_start = map.prev_line_boundary(start).0;
5632 let buffer_end = map.next_line_boundary(end).0;
5633 buffer_start.row..buffer_end.row + 1
5634 }
5635}
5636
5637impl<T: InvalidationRegion> InvalidationStack<T> {
5638 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
5639 where
5640 S: Clone + ToOffset,
5641 {
5642 while let Some(region) = self.last() {
5643 let all_selections_inside_invalidation_ranges =
5644 if selections.len() == region.ranges().len() {
5645 selections
5646 .iter()
5647 .zip(region.ranges().iter().map(|r| r.to_offset(&buffer)))
5648 .all(|(selection, invalidation_range)| {
5649 let head = selection.head().to_offset(&buffer);
5650 invalidation_range.start <= head && invalidation_range.end >= head
5651 })
5652 } else {
5653 false
5654 };
5655
5656 if all_selections_inside_invalidation_ranges {
5657 break;
5658 } else {
5659 self.pop();
5660 }
5661 }
5662 }
5663}
5664
5665impl<T> Default for InvalidationStack<T> {
5666 fn default() -> Self {
5667 Self(Default::default())
5668 }
5669}
5670
5671impl<T> Deref for InvalidationStack<T> {
5672 type Target = Vec<T>;
5673
5674 fn deref(&self) -> &Self::Target {
5675 &self.0
5676 }
5677}
5678
5679impl<T> DerefMut for InvalidationStack<T> {
5680 fn deref_mut(&mut self) -> &mut Self::Target {
5681 &mut self.0
5682 }
5683}
5684
5685impl InvalidationRegion for BracketPairState {
5686 fn ranges(&self) -> &[Range<Anchor>] {
5687 &self.ranges
5688 }
5689}
5690
5691impl InvalidationRegion for SnippetState {
5692 fn ranges(&self) -> &[Range<Anchor>] {
5693 &self.ranges[self.active_index]
5694 }
5695}
5696
5697impl Deref for EditorStyle {
5698 type Target = theme::Editor;
5699
5700 fn deref(&self) -> &Self::Target {
5701 &self.theme
5702 }
5703}
5704
5705pub fn diagnostic_block_renderer(
5706 diagnostic: Diagnostic,
5707 is_valid: bool,
5708 settings: watch::Receiver<Settings>,
5709) -> RenderBlock {
5710 let mut highlighted_lines = Vec::new();
5711 for line in diagnostic.message.lines() {
5712 highlighted_lines.push(highlight_diagnostic_message(line));
5713 }
5714
5715 Arc::new(move |cx: &BlockContext| {
5716 let settings = settings.borrow();
5717 let theme = &settings.theme.editor;
5718 let style = diagnostic_style(diagnostic.severity, is_valid, theme);
5719 let font_size = (style.text_scale_factor * settings.buffer_font_size).round();
5720 Flex::column()
5721 .with_children(highlighted_lines.iter().map(|(line, highlights)| {
5722 Label::new(
5723 line.clone(),
5724 style.message.clone().with_font_size(font_size),
5725 )
5726 .with_highlights(highlights.clone())
5727 .contained()
5728 .with_margin_left(cx.anchor_x)
5729 .boxed()
5730 }))
5731 .aligned()
5732 .left()
5733 .boxed()
5734 })
5735}
5736
5737pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
5738 let mut message_without_backticks = String::new();
5739 let mut prev_offset = 0;
5740 let mut inside_block = false;
5741 let mut highlights = Vec::new();
5742 for (match_ix, (offset, _)) in message
5743 .match_indices('`')
5744 .chain([(message.len(), "")])
5745 .enumerate()
5746 {
5747 message_without_backticks.push_str(&message[prev_offset..offset]);
5748 if inside_block {
5749 highlights.extend(prev_offset - match_ix..offset - match_ix);
5750 }
5751
5752 inside_block = !inside_block;
5753 prev_offset = offset + 1;
5754 }
5755
5756 (message_without_backticks, highlights)
5757}
5758
5759pub fn diagnostic_style(
5760 severity: DiagnosticSeverity,
5761 valid: bool,
5762 theme: &theme::Editor,
5763) -> DiagnosticStyle {
5764 match (severity, valid) {
5765 (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
5766 (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
5767 (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
5768 (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
5769 (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
5770 (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
5771 (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
5772 (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
5773 _ => theme.invalid_hint_diagnostic.clone(),
5774 }
5775}
5776
5777pub fn combine_syntax_and_fuzzy_match_highlights(
5778 text: &str,
5779 default_style: HighlightStyle,
5780 syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
5781 match_indices: &[usize],
5782) -> Vec<(Range<usize>, HighlightStyle)> {
5783 let mut result = Vec::new();
5784 let mut match_indices = match_indices.iter().copied().peekable();
5785
5786 for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
5787 {
5788 syntax_highlight.font_properties.weight(Default::default());
5789
5790 // Add highlights for any fuzzy match characters before the next
5791 // syntax highlight range.
5792 while let Some(&match_index) = match_indices.peek() {
5793 if match_index >= range.start {
5794 break;
5795 }
5796 match_indices.next();
5797 let end_index = char_ix_after(match_index, text);
5798 let mut match_style = default_style;
5799 match_style.font_properties.weight(fonts::Weight::BOLD);
5800 result.push((match_index..end_index, match_style));
5801 }
5802
5803 if range.start == usize::MAX {
5804 break;
5805 }
5806
5807 // Add highlights for any fuzzy match characters within the
5808 // syntax highlight range.
5809 let mut offset = range.start;
5810 while let Some(&match_index) = match_indices.peek() {
5811 if match_index >= range.end {
5812 break;
5813 }
5814
5815 match_indices.next();
5816 if match_index > offset {
5817 result.push((offset..match_index, syntax_highlight));
5818 }
5819
5820 let mut end_index = char_ix_after(match_index, text);
5821 while let Some(&next_match_index) = match_indices.peek() {
5822 if next_match_index == end_index && next_match_index < range.end {
5823 end_index = char_ix_after(next_match_index, text);
5824 match_indices.next();
5825 } else {
5826 break;
5827 }
5828 }
5829
5830 let mut match_style = syntax_highlight;
5831 match_style.font_properties.weight(fonts::Weight::BOLD);
5832 result.push((match_index..end_index, match_style));
5833 offset = end_index;
5834 }
5835
5836 if offset < range.end {
5837 result.push((offset..range.end, syntax_highlight));
5838 }
5839 }
5840
5841 fn char_ix_after(ix: usize, text: &str) -> usize {
5842 ix + text[ix..].chars().next().unwrap().len_utf8()
5843 }
5844
5845 result
5846}
5847
5848pub fn styled_runs_for_code_label<'a>(
5849 label: &'a CodeLabel,
5850 default_color: Color,
5851 syntax_theme: &'a theme::SyntaxTheme,
5852) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
5853 const MUTED_OPACITY: usize = 165;
5854
5855 let mut muted_default_style = HighlightStyle {
5856 color: default_color,
5857 ..Default::default()
5858 };
5859 muted_default_style.color.a = ((default_color.a as usize * MUTED_OPACITY) / 255) as u8;
5860
5861 let mut prev_end = label.filter_range.end;
5862 label
5863 .runs
5864 .iter()
5865 .enumerate()
5866 .flat_map(move |(ix, (range, highlight_id))| {
5867 let style = if let Some(style) = highlight_id.style(syntax_theme) {
5868 style
5869 } else {
5870 return Default::default();
5871 };
5872 let mut muted_style = style.clone();
5873 muted_style.color.a = ((style.color.a as usize * MUTED_OPACITY) / 255) as u8;
5874
5875 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
5876 if range.start >= label.filter_range.end {
5877 if range.start > prev_end {
5878 runs.push((prev_end..range.start, muted_default_style));
5879 }
5880 runs.push((range.clone(), muted_style));
5881 } else if range.end <= label.filter_range.end {
5882 runs.push((range.clone(), style));
5883 } else {
5884 runs.push((range.start..label.filter_range.end, style));
5885 runs.push((label.filter_range.end..range.end, muted_style));
5886 }
5887 prev_end = cmp::max(prev_end, range.end);
5888
5889 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
5890 runs.push((prev_end..label.text.len(), muted_default_style));
5891 }
5892
5893 runs
5894 })
5895}
5896
5897#[cfg(test)]
5898mod tests {
5899 use super::*;
5900 use language::LanguageConfig;
5901 use lsp::FakeLanguageServer;
5902 use project::{FakeFs, ProjectPath};
5903 use smol::stream::StreamExt;
5904 use std::{cell::RefCell, rc::Rc, time::Instant};
5905 use text::Point;
5906 use unindent::Unindent;
5907 use util::test::sample_text;
5908
5909 #[gpui::test]
5910 fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
5911 let mut now = Instant::now();
5912 let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
5913 let group_interval = buffer.read(cx).transaction_group_interval();
5914 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5915 let settings = Settings::test(cx);
5916 let (_, editor) = cx.add_window(Default::default(), |cx| {
5917 build_editor(buffer.clone(), settings, cx)
5918 });
5919
5920 editor.update(cx, |editor, cx| {
5921 editor.start_transaction_at(now, cx);
5922 editor.select_ranges([2..4], None, cx);
5923 editor.insert("cd", cx);
5924 editor.end_transaction_at(now, cx);
5925 assert_eq!(editor.text(cx), "12cd56");
5926 assert_eq!(editor.selected_ranges(cx), vec![4..4]);
5927
5928 editor.start_transaction_at(now, cx);
5929 editor.select_ranges([4..5], None, cx);
5930 editor.insert("e", cx);
5931 editor.end_transaction_at(now, cx);
5932 assert_eq!(editor.text(cx), "12cde6");
5933 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5934
5935 now += group_interval + Duration::from_millis(1);
5936 editor.select_ranges([2..2], None, cx);
5937
5938 // Simulate an edit in another editor
5939 buffer.update(cx, |buffer, cx| {
5940 buffer.start_transaction_at(now, cx);
5941 buffer.edit([0..1], "a", cx);
5942 buffer.edit([1..1], "b", cx);
5943 buffer.end_transaction_at(now, cx);
5944 });
5945
5946 assert_eq!(editor.text(cx), "ab2cde6");
5947 assert_eq!(editor.selected_ranges(cx), vec![3..3]);
5948
5949 // Last transaction happened past the group interval in a different editor.
5950 // Undo it individually and don't restore selections.
5951 editor.undo(&Undo, cx);
5952 assert_eq!(editor.text(cx), "12cde6");
5953 assert_eq!(editor.selected_ranges(cx), vec![2..2]);
5954
5955 // First two transactions happened within the group interval in this editor.
5956 // Undo them together and restore selections.
5957 editor.undo(&Undo, cx);
5958 editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
5959 assert_eq!(editor.text(cx), "123456");
5960 assert_eq!(editor.selected_ranges(cx), vec![0..0]);
5961
5962 // Redo the first two transactions together.
5963 editor.redo(&Redo, cx);
5964 assert_eq!(editor.text(cx), "12cde6");
5965 assert_eq!(editor.selected_ranges(cx), vec![5..5]);
5966
5967 // Redo the last transaction on its own.
5968 editor.redo(&Redo, cx);
5969 assert_eq!(editor.text(cx), "ab2cde6");
5970 assert_eq!(editor.selected_ranges(cx), vec![6..6]);
5971
5972 // Test empty transactions.
5973 editor.start_transaction_at(now, cx);
5974 editor.end_transaction_at(now, cx);
5975 editor.undo(&Undo, cx);
5976 assert_eq!(editor.text(cx), "12cde6");
5977 });
5978 }
5979
5980 #[gpui::test]
5981 fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
5982 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
5983 let settings = Settings::test(cx);
5984 let (_, editor) =
5985 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5986
5987 editor.update(cx, |view, cx| {
5988 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
5989 });
5990
5991 assert_eq!(
5992 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
5993 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
5994 );
5995
5996 editor.update(cx, |view, cx| {
5997 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
5998 });
5999
6000 assert_eq!(
6001 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6002 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6003 );
6004
6005 editor.update(cx, |view, cx| {
6006 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6007 });
6008
6009 assert_eq!(
6010 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6011 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6012 );
6013
6014 editor.update(cx, |view, cx| {
6015 view.end_selection(cx);
6016 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6017 });
6018
6019 assert_eq!(
6020 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6021 [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
6022 );
6023
6024 editor.update(cx, |view, cx| {
6025 view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
6026 view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
6027 });
6028
6029 assert_eq!(
6030 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6031 [
6032 DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
6033 DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
6034 ]
6035 );
6036
6037 editor.update(cx, |view, cx| {
6038 view.end_selection(cx);
6039 });
6040
6041 assert_eq!(
6042 editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
6043 [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
6044 );
6045 }
6046
6047 #[gpui::test]
6048 fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
6049 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6050 let settings = Settings::test(cx);
6051 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6052
6053 view.update(cx, |view, cx| {
6054 view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
6055 assert_eq!(
6056 view.selected_display_ranges(cx),
6057 [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
6058 );
6059 });
6060
6061 view.update(cx, |view, cx| {
6062 view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
6063 assert_eq!(
6064 view.selected_display_ranges(cx),
6065 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6066 );
6067 });
6068
6069 view.update(cx, |view, cx| {
6070 view.cancel(&Cancel, cx);
6071 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6072 assert_eq!(
6073 view.selected_display_ranges(cx),
6074 [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
6075 );
6076 });
6077 }
6078
6079 #[gpui::test]
6080 fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
6081 cx.add_window(Default::default(), |cx| {
6082 use workspace::ItemView;
6083 let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
6084 let settings = Settings::test(&cx);
6085 let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
6086 let mut editor = build_editor(buffer.clone(), settings, cx);
6087 editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
6088
6089 // Move the cursor a small distance.
6090 // Nothing is added to the navigation history.
6091 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
6092 editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
6093 assert!(nav_history.borrow_mut().pop_backward().is_none());
6094
6095 // Move the cursor a large distance.
6096 // The history can jump back to the previous position.
6097 editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
6098 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6099 editor.navigate(nav_entry.data.unwrap(), cx);
6100 assert_eq!(nav_entry.item_view.id(), cx.view_id());
6101 assert_eq!(
6102 editor.selected_display_ranges(cx),
6103 &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
6104 );
6105
6106 // Move the cursor a small distance via the mouse.
6107 // Nothing is added to the navigation history.
6108 editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
6109 editor.end_selection(cx);
6110 assert_eq!(
6111 editor.selected_display_ranges(cx),
6112 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6113 );
6114 assert!(nav_history.borrow_mut().pop_backward().is_none());
6115
6116 // Move the cursor a large distance via the mouse.
6117 // The history can jump back to the previous position.
6118 editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
6119 editor.end_selection(cx);
6120 assert_eq!(
6121 editor.selected_display_ranges(cx),
6122 &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
6123 );
6124 let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
6125 editor.navigate(nav_entry.data.unwrap(), cx);
6126 assert_eq!(nav_entry.item_view.id(), cx.view_id());
6127 assert_eq!(
6128 editor.selected_display_ranges(cx),
6129 &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
6130 );
6131
6132 editor
6133 });
6134 }
6135
6136 #[gpui::test]
6137 fn test_cancel(cx: &mut gpui::MutableAppContext) {
6138 let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
6139 let settings = Settings::test(cx);
6140 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6141
6142 view.update(cx, |view, cx| {
6143 view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
6144 view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
6145 view.end_selection(cx);
6146
6147 view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
6148 view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
6149 view.end_selection(cx);
6150 assert_eq!(
6151 view.selected_display_ranges(cx),
6152 [
6153 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
6154 DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
6155 ]
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(3, 4)..DisplayPoint::new(1, 1)]
6164 );
6165 });
6166
6167 view.update(cx, |view, cx| {
6168 view.cancel(&Cancel, cx);
6169 assert_eq!(
6170 view.selected_display_ranges(cx),
6171 [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
6172 );
6173 });
6174 }
6175
6176 #[gpui::test]
6177 fn test_fold(cx: &mut gpui::MutableAppContext) {
6178 let buffer = MultiBuffer::build_simple(
6179 &"
6180 impl Foo {
6181 // Hello!
6182
6183 fn a() {
6184 1
6185 }
6186
6187 fn b() {
6188 2
6189 }
6190
6191 fn c() {
6192 3
6193 }
6194 }
6195 "
6196 .unindent(),
6197 cx,
6198 );
6199 let settings = Settings::test(&cx);
6200 let (_, view) = cx.add_window(Default::default(), |cx| {
6201 build_editor(buffer.clone(), settings, cx)
6202 });
6203
6204 view.update(cx, |view, cx| {
6205 view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
6206 view.fold(&Fold, cx);
6207 assert_eq!(
6208 view.display_text(cx),
6209 "
6210 impl Foo {
6211 // Hello!
6212
6213 fn a() {
6214 1
6215 }
6216
6217 fn b() {…
6218 }
6219
6220 fn c() {…
6221 }
6222 }
6223 "
6224 .unindent(),
6225 );
6226
6227 view.fold(&Fold, cx);
6228 assert_eq!(
6229 view.display_text(cx),
6230 "
6231 impl Foo {…
6232 }
6233 "
6234 .unindent(),
6235 );
6236
6237 view.unfold(&Unfold, cx);
6238 assert_eq!(
6239 view.display_text(cx),
6240 "
6241 impl Foo {
6242 // Hello!
6243
6244 fn a() {
6245 1
6246 }
6247
6248 fn b() {…
6249 }
6250
6251 fn c() {…
6252 }
6253 }
6254 "
6255 .unindent(),
6256 );
6257
6258 view.unfold(&Unfold, cx);
6259 assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
6260 });
6261 }
6262
6263 #[gpui::test]
6264 fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
6265 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6266 let settings = Settings::test(&cx);
6267 let (_, view) = cx.add_window(Default::default(), |cx| {
6268 build_editor(buffer.clone(), settings, cx)
6269 });
6270
6271 buffer.update(cx, |buffer, cx| {
6272 buffer.edit(
6273 vec![
6274 Point::new(1, 0)..Point::new(1, 0),
6275 Point::new(1, 1)..Point::new(1, 1),
6276 ],
6277 "\t",
6278 cx,
6279 );
6280 });
6281
6282 view.update(cx, |view, cx| {
6283 assert_eq!(
6284 view.selected_display_ranges(cx),
6285 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6286 );
6287
6288 view.move_down(&MoveDown, cx);
6289 assert_eq!(
6290 view.selected_display_ranges(cx),
6291 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6292 );
6293
6294 view.move_right(&MoveRight, cx);
6295 assert_eq!(
6296 view.selected_display_ranges(cx),
6297 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
6298 );
6299
6300 view.move_left(&MoveLeft, cx);
6301 assert_eq!(
6302 view.selected_display_ranges(cx),
6303 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
6304 );
6305
6306 view.move_up(&MoveUp, cx);
6307 assert_eq!(
6308 view.selected_display_ranges(cx),
6309 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6310 );
6311
6312 view.move_to_end(&MoveToEnd, cx);
6313 assert_eq!(
6314 view.selected_display_ranges(cx),
6315 &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
6316 );
6317
6318 view.move_to_beginning(&MoveToBeginning, cx);
6319 assert_eq!(
6320 view.selected_display_ranges(cx),
6321 &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
6322 );
6323
6324 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
6325 view.select_to_beginning(&SelectToBeginning, cx);
6326 assert_eq!(
6327 view.selected_display_ranges(cx),
6328 &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
6329 );
6330
6331 view.select_to_end(&SelectToEnd, cx);
6332 assert_eq!(
6333 view.selected_display_ranges(cx),
6334 &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
6335 );
6336 });
6337 }
6338
6339 #[gpui::test]
6340 fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
6341 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
6342 let settings = Settings::test(&cx);
6343 let (_, view) = cx.add_window(Default::default(), |cx| {
6344 build_editor(buffer.clone(), settings, cx)
6345 });
6346
6347 assert_eq!('ⓐ'.len_utf8(), 3);
6348 assert_eq!('α'.len_utf8(), 2);
6349
6350 view.update(cx, |view, cx| {
6351 view.fold_ranges(
6352 vec![
6353 Point::new(0, 6)..Point::new(0, 12),
6354 Point::new(1, 2)..Point::new(1, 4),
6355 Point::new(2, 4)..Point::new(2, 8),
6356 ],
6357 cx,
6358 );
6359 assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
6360
6361 view.move_right(&MoveRight, cx);
6362 assert_eq!(
6363 view.selected_display_ranges(cx),
6364 &[empty_range(0, "ⓐ".len())]
6365 );
6366 view.move_right(&MoveRight, cx);
6367 assert_eq!(
6368 view.selected_display_ranges(cx),
6369 &[empty_range(0, "ⓐⓑ".len())]
6370 );
6371 view.move_right(&MoveRight, cx);
6372 assert_eq!(
6373 view.selected_display_ranges(cx),
6374 &[empty_range(0, "ⓐⓑ…".len())]
6375 );
6376
6377 view.move_down(&MoveDown, cx);
6378 assert_eq!(
6379 view.selected_display_ranges(cx),
6380 &[empty_range(1, "ab…".len())]
6381 );
6382 view.move_left(&MoveLeft, cx);
6383 assert_eq!(
6384 view.selected_display_ranges(cx),
6385 &[empty_range(1, "ab".len())]
6386 );
6387 view.move_left(&MoveLeft, cx);
6388 assert_eq!(
6389 view.selected_display_ranges(cx),
6390 &[empty_range(1, "a".len())]
6391 );
6392
6393 view.move_down(&MoveDown, cx);
6394 assert_eq!(
6395 view.selected_display_ranges(cx),
6396 &[empty_range(2, "α".len())]
6397 );
6398 view.move_right(&MoveRight, cx);
6399 assert_eq!(
6400 view.selected_display_ranges(cx),
6401 &[empty_range(2, "αβ".len())]
6402 );
6403 view.move_right(&MoveRight, cx);
6404 assert_eq!(
6405 view.selected_display_ranges(cx),
6406 &[empty_range(2, "αβ…".len())]
6407 );
6408 view.move_right(&MoveRight, cx);
6409 assert_eq!(
6410 view.selected_display_ranges(cx),
6411 &[empty_range(2, "αβ…ε".len())]
6412 );
6413
6414 view.move_up(&MoveUp, cx);
6415 assert_eq!(
6416 view.selected_display_ranges(cx),
6417 &[empty_range(1, "ab…e".len())]
6418 );
6419 view.move_up(&MoveUp, cx);
6420 assert_eq!(
6421 view.selected_display_ranges(cx),
6422 &[empty_range(0, "ⓐⓑ…ⓔ".len())]
6423 );
6424 view.move_left(&MoveLeft, cx);
6425 assert_eq!(
6426 view.selected_display_ranges(cx),
6427 &[empty_range(0, "ⓐⓑ…".len())]
6428 );
6429 view.move_left(&MoveLeft, cx);
6430 assert_eq!(
6431 view.selected_display_ranges(cx),
6432 &[empty_range(0, "ⓐⓑ".len())]
6433 );
6434 view.move_left(&MoveLeft, cx);
6435 assert_eq!(
6436 view.selected_display_ranges(cx),
6437 &[empty_range(0, "ⓐ".len())]
6438 );
6439 });
6440 }
6441
6442 #[gpui::test]
6443 fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
6444 let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
6445 let settings = Settings::test(&cx);
6446 let (_, view) = cx.add_window(Default::default(), |cx| {
6447 build_editor(buffer.clone(), settings, cx)
6448 });
6449 view.update(cx, |view, cx| {
6450 view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
6451 view.move_down(&MoveDown, cx);
6452 assert_eq!(
6453 view.selected_display_ranges(cx),
6454 &[empty_range(1, "abcd".len())]
6455 );
6456
6457 view.move_down(&MoveDown, cx);
6458 assert_eq!(
6459 view.selected_display_ranges(cx),
6460 &[empty_range(2, "αβγ".len())]
6461 );
6462
6463 view.move_down(&MoveDown, cx);
6464 assert_eq!(
6465 view.selected_display_ranges(cx),
6466 &[empty_range(3, "abcd".len())]
6467 );
6468
6469 view.move_down(&MoveDown, cx);
6470 assert_eq!(
6471 view.selected_display_ranges(cx),
6472 &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
6473 );
6474
6475 view.move_up(&MoveUp, cx);
6476 assert_eq!(
6477 view.selected_display_ranges(cx),
6478 &[empty_range(3, "abcd".len())]
6479 );
6480
6481 view.move_up(&MoveUp, cx);
6482 assert_eq!(
6483 view.selected_display_ranges(cx),
6484 &[empty_range(2, "αβγ".len())]
6485 );
6486 });
6487 }
6488
6489 #[gpui::test]
6490 fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
6491 let buffer = MultiBuffer::build_simple("abc\n def", cx);
6492 let settings = Settings::test(&cx);
6493 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6494 view.update(cx, |view, cx| {
6495 view.select_display_ranges(
6496 &[
6497 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6498 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6499 ],
6500 cx,
6501 );
6502 });
6503
6504 view.update(cx, |view, cx| {
6505 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6506 assert_eq!(
6507 view.selected_display_ranges(cx),
6508 &[
6509 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6510 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6511 ]
6512 );
6513 });
6514
6515 view.update(cx, |view, cx| {
6516 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6517 assert_eq!(
6518 view.selected_display_ranges(cx),
6519 &[
6520 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6521 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6522 ]
6523 );
6524 });
6525
6526 view.update(cx, |view, cx| {
6527 view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
6528 assert_eq!(
6529 view.selected_display_ranges(cx),
6530 &[
6531 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6532 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6533 ]
6534 );
6535 });
6536
6537 view.update(cx, |view, cx| {
6538 view.move_to_end_of_line(&MoveToEndOfLine, cx);
6539 assert_eq!(
6540 view.selected_display_ranges(cx),
6541 &[
6542 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6543 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6544 ]
6545 );
6546 });
6547
6548 // Moving to the end of line again is a no-op.
6549 view.update(cx, |view, cx| {
6550 view.move_to_end_of_line(&MoveToEndOfLine, cx);
6551 assert_eq!(
6552 view.selected_display_ranges(cx),
6553 &[
6554 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6555 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
6556 ]
6557 );
6558 });
6559
6560 view.update(cx, |view, cx| {
6561 view.move_left(&MoveLeft, cx);
6562 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6563 assert_eq!(
6564 view.selected_display_ranges(cx),
6565 &[
6566 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6567 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6568 ]
6569 );
6570 });
6571
6572 view.update(cx, |view, cx| {
6573 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6574 assert_eq!(
6575 view.selected_display_ranges(cx),
6576 &[
6577 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6578 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
6579 ]
6580 );
6581 });
6582
6583 view.update(cx, |view, cx| {
6584 view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
6585 assert_eq!(
6586 view.selected_display_ranges(cx),
6587 &[
6588 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
6589 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
6590 ]
6591 );
6592 });
6593
6594 view.update(cx, |view, cx| {
6595 view.select_to_end_of_line(&SelectToEndOfLine(true), cx);
6596 assert_eq!(
6597 view.selected_display_ranges(cx),
6598 &[
6599 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6600 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
6601 ]
6602 );
6603 });
6604
6605 view.update(cx, |view, cx| {
6606 view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
6607 assert_eq!(view.display_text(cx), "ab\n de");
6608 assert_eq!(
6609 view.selected_display_ranges(cx),
6610 &[
6611 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6612 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
6613 ]
6614 );
6615 });
6616
6617 view.update(cx, |view, cx| {
6618 view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
6619 assert_eq!(view.display_text(cx), "\n");
6620 assert_eq!(
6621 view.selected_display_ranges(cx),
6622 &[
6623 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6624 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6625 ]
6626 );
6627 });
6628 }
6629
6630 #[gpui::test]
6631 fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
6632 let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n {baz.qux()}", cx);
6633 let settings = Settings::test(&cx);
6634 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6635 view.update(cx, |view, cx| {
6636 view.select_display_ranges(
6637 &[
6638 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
6639 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
6640 ],
6641 cx,
6642 );
6643 });
6644
6645 view.update(cx, |view, cx| {
6646 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6647 assert_eq!(
6648 view.selected_display_ranges(cx),
6649 &[
6650 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6651 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6652 ]
6653 );
6654 });
6655
6656 view.update(cx, |view, cx| {
6657 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6658 assert_eq!(
6659 view.selected_display_ranges(cx),
6660 &[
6661 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6662 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
6663 ]
6664 );
6665 });
6666
6667 view.update(cx, |view, cx| {
6668 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6669 assert_eq!(
6670 view.selected_display_ranges(cx),
6671 &[
6672 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
6673 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6674 ]
6675 );
6676 });
6677
6678 view.update(cx, |view, cx| {
6679 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6680 assert_eq!(
6681 view.selected_display_ranges(cx),
6682 &[
6683 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6684 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6685 ]
6686 );
6687 });
6688
6689 view.update(cx, |view, cx| {
6690 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6691 assert_eq!(
6692 view.selected_display_ranges(cx),
6693 &[
6694 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6695 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
6696 ]
6697 );
6698 });
6699
6700 view.update(cx, |view, cx| {
6701 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6702 assert_eq!(
6703 view.selected_display_ranges(cx),
6704 &[
6705 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6706 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
6707 ]
6708 );
6709 });
6710
6711 view.update(cx, |view, cx| {
6712 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6713 assert_eq!(
6714 view.selected_display_ranges(cx),
6715 &[
6716 DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
6717 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6718 ]
6719 );
6720 });
6721
6722 view.update(cx, |view, cx| {
6723 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6724 assert_eq!(
6725 view.selected_display_ranges(cx),
6726 &[
6727 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
6728 DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6729 ]
6730 );
6731 });
6732
6733 view.update(cx, |view, cx| {
6734 view.move_right(&MoveRight, cx);
6735 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6736 assert_eq!(
6737 view.selected_display_ranges(cx),
6738 &[
6739 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6740 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6741 ]
6742 );
6743 });
6744
6745 view.update(cx, |view, cx| {
6746 view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
6747 assert_eq!(
6748 view.selected_display_ranges(cx),
6749 &[
6750 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
6751 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
6752 ]
6753 );
6754 });
6755
6756 view.update(cx, |view, cx| {
6757 view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
6758 assert_eq!(
6759 view.selected_display_ranges(cx),
6760 &[
6761 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
6762 DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
6763 ]
6764 );
6765 });
6766 }
6767
6768 #[gpui::test]
6769 fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
6770 let buffer = MultiBuffer::build_simple("use one::{\n two::three::four::five\n};", cx);
6771 let settings = Settings::test(&cx);
6772 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
6773
6774 view.update(cx, |view, cx| {
6775 view.set_wrap_width(Some(140.), cx);
6776 assert_eq!(
6777 view.display_text(cx),
6778 "use one::{\n two::three::\n four::five\n};"
6779 );
6780
6781 view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
6782
6783 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6784 assert_eq!(
6785 view.selected_display_ranges(cx),
6786 &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
6787 );
6788
6789 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6790 assert_eq!(
6791 view.selected_display_ranges(cx),
6792 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6793 );
6794
6795 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6796 assert_eq!(
6797 view.selected_display_ranges(cx),
6798 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6799 );
6800
6801 view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
6802 assert_eq!(
6803 view.selected_display_ranges(cx),
6804 &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
6805 );
6806
6807 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6808 assert_eq!(
6809 view.selected_display_ranges(cx),
6810 &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
6811 );
6812
6813 view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
6814 assert_eq!(
6815 view.selected_display_ranges(cx),
6816 &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
6817 );
6818 });
6819 }
6820
6821 #[gpui::test]
6822 fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
6823 let buffer = MultiBuffer::build_simple("one two three four", cx);
6824 let settings = Settings::test(&cx);
6825 let (_, view) = cx.add_window(Default::default(), |cx| {
6826 build_editor(buffer.clone(), settings, cx)
6827 });
6828
6829 view.update(cx, |view, cx| {
6830 view.select_display_ranges(
6831 &[
6832 // an empty selection - the preceding word fragment is deleted
6833 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6834 // characters selected - they are deleted
6835 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
6836 ],
6837 cx,
6838 );
6839 view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
6840 });
6841
6842 assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
6843
6844 view.update(cx, |view, cx| {
6845 view.select_display_ranges(
6846 &[
6847 // an empty selection - the following word fragment is deleted
6848 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
6849 // characters selected - they are deleted
6850 DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
6851 ],
6852 cx,
6853 );
6854 view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
6855 });
6856
6857 assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
6858 }
6859
6860 #[gpui::test]
6861 fn test_newline(cx: &mut gpui::MutableAppContext) {
6862 let buffer = MultiBuffer::build_simple("aaaa\n bbbb\n", cx);
6863 let settings = Settings::test(&cx);
6864 let (_, view) = cx.add_window(Default::default(), |cx| {
6865 build_editor(buffer.clone(), settings, cx)
6866 });
6867
6868 view.update(cx, |view, cx| {
6869 view.select_display_ranges(
6870 &[
6871 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
6872 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6873 DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
6874 ],
6875 cx,
6876 );
6877
6878 view.newline(&Newline, cx);
6879 assert_eq!(view.text(cx), "aa\naa\n \n bb\n bb\n");
6880 });
6881 }
6882
6883 #[gpui::test]
6884 fn test_newline_with_old_selections(cx: &mut gpui::MutableAppContext) {
6885 let buffer = MultiBuffer::build_simple(
6886 "
6887 a
6888 b(
6889 X
6890 )
6891 c(
6892 X
6893 )
6894 "
6895 .unindent()
6896 .as_str(),
6897 cx,
6898 );
6899
6900 let settings = Settings::test(&cx);
6901 let (_, editor) = cx.add_window(Default::default(), |cx| {
6902 let mut editor = build_editor(buffer.clone(), settings, cx);
6903 editor.select_ranges(
6904 [
6905 Point::new(2, 4)..Point::new(2, 5),
6906 Point::new(5, 4)..Point::new(5, 5),
6907 ],
6908 None,
6909 cx,
6910 );
6911 editor
6912 });
6913
6914 // Edit the buffer directly, deleting ranges surrounding the editor's selections
6915 buffer.update(cx, |buffer, cx| {
6916 buffer.edit(
6917 [
6918 Point::new(1, 2)..Point::new(3, 0),
6919 Point::new(4, 2)..Point::new(6, 0),
6920 ],
6921 "",
6922 cx,
6923 );
6924 assert_eq!(
6925 buffer.read(cx).text(),
6926 "
6927 a
6928 b()
6929 c()
6930 "
6931 .unindent()
6932 );
6933 });
6934
6935 editor.update(cx, |editor, cx| {
6936 assert_eq!(
6937 editor.selected_ranges(cx),
6938 &[
6939 Point::new(1, 2)..Point::new(1, 2),
6940 Point::new(2, 2)..Point::new(2, 2),
6941 ],
6942 );
6943
6944 editor.newline(&Newline, cx);
6945 assert_eq!(
6946 editor.text(cx),
6947 "
6948 a
6949 b(
6950 )
6951 c(
6952 )
6953 "
6954 .unindent()
6955 );
6956
6957 // The selections are moved after the inserted newlines
6958 assert_eq!(
6959 editor.selected_ranges(cx),
6960 &[
6961 Point::new(2, 0)..Point::new(2, 0),
6962 Point::new(4, 0)..Point::new(4, 0),
6963 ],
6964 );
6965 });
6966 }
6967
6968 #[gpui::test]
6969 fn test_insert_with_old_selections(cx: &mut gpui::MutableAppContext) {
6970 let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
6971
6972 let settings = Settings::test(&cx);
6973 let (_, editor) = cx.add_window(Default::default(), |cx| {
6974 let mut editor = build_editor(buffer.clone(), settings, cx);
6975 editor.select_ranges([3..4, 11..12, 19..20], None, cx);
6976 editor
6977 });
6978
6979 // Edit the buffer directly, deleting ranges surrounding the editor's selections
6980 buffer.update(cx, |buffer, cx| {
6981 buffer.edit([2..5, 10..13, 18..21], "", cx);
6982 assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
6983 });
6984
6985 editor.update(cx, |editor, cx| {
6986 assert_eq!(editor.selected_ranges(cx), &[2..2, 7..7, 12..12],);
6987
6988 editor.insert("Z", cx);
6989 assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
6990
6991 // The selections are moved after the inserted characters
6992 assert_eq!(editor.selected_ranges(cx), &[3..3, 9..9, 15..15],);
6993 });
6994 }
6995
6996 #[gpui::test]
6997 fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
6998 let buffer = MultiBuffer::build_simple(" one two\nthree\n four", cx);
6999 let settings = Settings::test(&cx);
7000 let (_, view) = cx.add_window(Default::default(), |cx| {
7001 build_editor(buffer.clone(), settings, cx)
7002 });
7003
7004 view.update(cx, |view, cx| {
7005 // two selections on the same line
7006 view.select_display_ranges(
7007 &[
7008 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
7009 DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
7010 ],
7011 cx,
7012 );
7013
7014 // indent from mid-tabstop to full tabstop
7015 view.tab(&Tab, cx);
7016 assert_eq!(view.text(cx), " one two\nthree\n four");
7017 assert_eq!(
7018 view.selected_display_ranges(cx),
7019 &[
7020 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7021 DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
7022 ]
7023 );
7024
7025 // outdent from 1 tabstop to 0 tabstops
7026 view.outdent(&Outdent, cx);
7027 assert_eq!(view.text(cx), "one two\nthree\n four");
7028 assert_eq!(
7029 view.selected_display_ranges(cx),
7030 &[
7031 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
7032 DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
7033 ]
7034 );
7035
7036 // select across line ending
7037 view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
7038
7039 // indent and outdent affect only the preceding line
7040 view.tab(&Tab, cx);
7041 assert_eq!(view.text(cx), "one two\n three\n four");
7042 assert_eq!(
7043 view.selected_display_ranges(cx),
7044 &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
7045 );
7046 view.outdent(&Outdent, cx);
7047 assert_eq!(view.text(cx), "one two\nthree\n four");
7048 assert_eq!(
7049 view.selected_display_ranges(cx),
7050 &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
7051 );
7052
7053 // Ensure that indenting/outdenting works when the cursor is at column 0.
7054 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7055 view.tab(&Tab, cx);
7056 assert_eq!(view.text(cx), "one two\n three\n four");
7057 assert_eq!(
7058 view.selected_display_ranges(cx),
7059 &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
7060 );
7061
7062 view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
7063 view.outdent(&Outdent, cx);
7064 assert_eq!(view.text(cx), "one two\nthree\n four");
7065 assert_eq!(
7066 view.selected_display_ranges(cx),
7067 &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
7068 );
7069 });
7070 }
7071
7072 #[gpui::test]
7073 fn test_backspace(cx: &mut gpui::MutableAppContext) {
7074 let buffer =
7075 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7076 let settings = Settings::test(&cx);
7077 let (_, view) = cx.add_window(Default::default(), |cx| {
7078 build_editor(buffer.clone(), settings, cx)
7079 });
7080
7081 view.update(cx, |view, cx| {
7082 view.select_display_ranges(
7083 &[
7084 // an empty selection - the preceding character is deleted
7085 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7086 // one character selected - it is deleted
7087 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7088 // a line suffix selected - it is deleted
7089 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7090 ],
7091 cx,
7092 );
7093 view.backspace(&Backspace, cx);
7094 });
7095
7096 assert_eq!(
7097 buffer.read(cx).read(cx).text(),
7098 "oe two three\nfou five six\nseven ten\n"
7099 );
7100 }
7101
7102 #[gpui::test]
7103 fn test_delete(cx: &mut gpui::MutableAppContext) {
7104 let buffer =
7105 MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
7106 let settings = Settings::test(&cx);
7107 let (_, view) = cx.add_window(Default::default(), |cx| {
7108 build_editor(buffer.clone(), settings, cx)
7109 });
7110
7111 view.update(cx, |view, cx| {
7112 view.select_display_ranges(
7113 &[
7114 // an empty selection - the following character is deleted
7115 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7116 // one character selected - it is deleted
7117 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7118 // a line suffix selected - it is deleted
7119 DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
7120 ],
7121 cx,
7122 );
7123 view.delete(&Delete, cx);
7124 });
7125
7126 assert_eq!(
7127 buffer.read(cx).read(cx).text(),
7128 "on two three\nfou five six\nseven ten\n"
7129 );
7130 }
7131
7132 #[gpui::test]
7133 fn test_delete_line(cx: &mut gpui::MutableAppContext) {
7134 let settings = Settings::test(&cx);
7135 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7136 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7137 view.update(cx, |view, cx| {
7138 view.select_display_ranges(
7139 &[
7140 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7141 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7142 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7143 ],
7144 cx,
7145 );
7146 view.delete_line(&DeleteLine, cx);
7147 assert_eq!(view.display_text(cx), "ghi");
7148 assert_eq!(
7149 view.selected_display_ranges(cx),
7150 vec![
7151 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
7152 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
7153 ]
7154 );
7155 });
7156
7157 let settings = Settings::test(&cx);
7158 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7159 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7160 view.update(cx, |view, cx| {
7161 view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
7162 view.delete_line(&DeleteLine, cx);
7163 assert_eq!(view.display_text(cx), "ghi\n");
7164 assert_eq!(
7165 view.selected_display_ranges(cx),
7166 vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
7167 );
7168 });
7169 }
7170
7171 #[gpui::test]
7172 fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
7173 let settings = Settings::test(&cx);
7174 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7175 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7176 view.update(cx, |view, cx| {
7177 view.select_display_ranges(
7178 &[
7179 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7180 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7181 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7182 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7183 ],
7184 cx,
7185 );
7186 view.duplicate_line(&DuplicateLine, cx);
7187 assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
7188 assert_eq!(
7189 view.selected_display_ranges(cx),
7190 vec![
7191 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
7192 DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
7193 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7194 DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
7195 ]
7196 );
7197 });
7198
7199 let settings = Settings::test(&cx);
7200 let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
7201 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7202 view.update(cx, |view, cx| {
7203 view.select_display_ranges(
7204 &[
7205 DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
7206 DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
7207 ],
7208 cx,
7209 );
7210 view.duplicate_line(&DuplicateLine, cx);
7211 assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
7212 assert_eq!(
7213 view.selected_display_ranges(cx),
7214 vec![
7215 DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
7216 DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
7217 ]
7218 );
7219 });
7220 }
7221
7222 #[gpui::test]
7223 fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
7224 let settings = Settings::test(&cx);
7225 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7226 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7227 view.update(cx, |view, cx| {
7228 view.fold_ranges(
7229 vec![
7230 Point::new(0, 2)..Point::new(1, 2),
7231 Point::new(2, 3)..Point::new(4, 1),
7232 Point::new(7, 0)..Point::new(8, 4),
7233 ],
7234 cx,
7235 );
7236 view.select_display_ranges(
7237 &[
7238 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7239 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7240 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7241 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
7242 ],
7243 cx,
7244 );
7245 assert_eq!(
7246 view.display_text(cx),
7247 "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
7248 );
7249
7250 view.move_line_up(&MoveLineUp, cx);
7251 assert_eq!(
7252 view.display_text(cx),
7253 "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
7254 );
7255 assert_eq!(
7256 view.selected_display_ranges(cx),
7257 vec![
7258 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7259 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7260 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7261 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7262 ]
7263 );
7264 });
7265
7266 view.update(cx, |view, cx| {
7267 view.move_line_down(&MoveLineDown, cx);
7268 assert_eq!(
7269 view.display_text(cx),
7270 "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
7271 );
7272 assert_eq!(
7273 view.selected_display_ranges(cx),
7274 vec![
7275 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7276 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7277 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7278 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7279 ]
7280 );
7281 });
7282
7283 view.update(cx, |view, cx| {
7284 view.move_line_down(&MoveLineDown, cx);
7285 assert_eq!(
7286 view.display_text(cx),
7287 "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
7288 );
7289 assert_eq!(
7290 view.selected_display_ranges(cx),
7291 vec![
7292 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7293 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
7294 DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
7295 DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
7296 ]
7297 );
7298 });
7299
7300 view.update(cx, |view, cx| {
7301 view.move_line_up(&MoveLineUp, cx);
7302 assert_eq!(
7303 view.display_text(cx),
7304 "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
7305 );
7306 assert_eq!(
7307 view.selected_display_ranges(cx),
7308 vec![
7309 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7310 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7311 DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
7312 DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
7313 ]
7314 );
7315 });
7316 }
7317
7318 #[gpui::test]
7319 fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
7320 let settings = Settings::test(&cx);
7321 let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
7322 let snapshot = buffer.read(cx).snapshot(cx);
7323 let (_, editor) =
7324 cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7325 editor.update(cx, |editor, cx| {
7326 editor.insert_blocks(
7327 [BlockProperties {
7328 position: snapshot.anchor_after(Point::new(2, 0)),
7329 disposition: BlockDisposition::Below,
7330 height: 1,
7331 render: Arc::new(|_| Empty::new().boxed()),
7332 }],
7333 cx,
7334 );
7335 editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
7336 editor.move_line_down(&MoveLineDown, cx);
7337 });
7338 }
7339
7340 #[gpui::test]
7341 fn test_clipboard(cx: &mut gpui::MutableAppContext) {
7342 let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
7343 let settings = Settings::test(&cx);
7344 let view = cx
7345 .add_window(Default::default(), |cx| {
7346 build_editor(buffer.clone(), settings, cx)
7347 })
7348 .1;
7349
7350 // Cut with three selections. Clipboard text is divided into three slices.
7351 view.update(cx, |view, cx| {
7352 view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
7353 view.cut(&Cut, cx);
7354 assert_eq!(view.display_text(cx), "two four six ");
7355 });
7356
7357 // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
7358 view.update(cx, |view, cx| {
7359 view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
7360 view.paste(&Paste, cx);
7361 assert_eq!(view.display_text(cx), "two one✅ four three six five ");
7362 assert_eq!(
7363 view.selected_display_ranges(cx),
7364 &[
7365 DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
7366 DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
7367 DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
7368 ]
7369 );
7370 });
7371
7372 // Paste again but with only two cursors. Since the number of cursors doesn't
7373 // match the number of slices in the clipboard, the entire clipboard text
7374 // is pasted at each cursor.
7375 view.update(cx, |view, cx| {
7376 view.select_ranges(vec![0..0, 31..31], None, cx);
7377 view.handle_input(&Input("( ".into()), cx);
7378 view.paste(&Paste, cx);
7379 view.handle_input(&Input(") ".into()), cx);
7380 assert_eq!(
7381 view.display_text(cx),
7382 "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7383 );
7384 });
7385
7386 view.update(cx, |view, cx| {
7387 view.select_ranges(vec![0..0], None, cx);
7388 view.handle_input(&Input("123\n4567\n89\n".into()), cx);
7389 assert_eq!(
7390 view.display_text(cx),
7391 "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7392 );
7393 });
7394
7395 // Cut with three selections, one of which is full-line.
7396 view.update(cx, |view, cx| {
7397 view.select_display_ranges(
7398 &[
7399 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
7400 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7401 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
7402 ],
7403 cx,
7404 );
7405 view.cut(&Cut, cx);
7406 assert_eq!(
7407 view.display_text(cx),
7408 "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
7409 );
7410 });
7411
7412 // Paste with three selections, noticing how the copied selection that was full-line
7413 // gets inserted before the second cursor.
7414 view.update(cx, |view, cx| {
7415 view.select_display_ranges(
7416 &[
7417 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7418 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7419 DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
7420 ],
7421 cx,
7422 );
7423 view.paste(&Paste, cx);
7424 assert_eq!(
7425 view.display_text(cx),
7426 "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7427 );
7428 assert_eq!(
7429 view.selected_display_ranges(cx),
7430 &[
7431 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7432 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7433 DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
7434 ]
7435 );
7436 });
7437
7438 // Copy with a single cursor only, which writes the whole line into the clipboard.
7439 view.update(cx, |view, cx| {
7440 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
7441 view.copy(&Copy, cx);
7442 });
7443
7444 // Paste with three selections, noticing how the copied full-line selection is inserted
7445 // before the empty selections but replaces the selection that is non-empty.
7446 view.update(cx, |view, cx| {
7447 view.select_display_ranges(
7448 &[
7449 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7450 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
7451 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
7452 ],
7453 cx,
7454 );
7455 view.paste(&Paste, cx);
7456 assert_eq!(
7457 view.display_text(cx),
7458 "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
7459 );
7460 assert_eq!(
7461 view.selected_display_ranges(cx),
7462 &[
7463 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
7464 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
7465 DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
7466 ]
7467 );
7468 });
7469 }
7470
7471 #[gpui::test]
7472 fn test_select_all(cx: &mut gpui::MutableAppContext) {
7473 let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
7474 let settings = Settings::test(&cx);
7475 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7476 view.update(cx, |view, cx| {
7477 view.select_all(&SelectAll, cx);
7478 assert_eq!(
7479 view.selected_display_ranges(cx),
7480 &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
7481 );
7482 });
7483 }
7484
7485 #[gpui::test]
7486 fn test_select_line(cx: &mut gpui::MutableAppContext) {
7487 let settings = Settings::test(&cx);
7488 let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
7489 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7490 view.update(cx, |view, cx| {
7491 view.select_display_ranges(
7492 &[
7493 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7494 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7495 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7496 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
7497 ],
7498 cx,
7499 );
7500 view.select_line(&SelectLine, cx);
7501 assert_eq!(
7502 view.selected_display_ranges(cx),
7503 vec![
7504 DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
7505 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
7506 ]
7507 );
7508 });
7509
7510 view.update(cx, |view, cx| {
7511 view.select_line(&SelectLine, cx);
7512 assert_eq!(
7513 view.selected_display_ranges(cx),
7514 vec![
7515 DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
7516 DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
7517 ]
7518 );
7519 });
7520
7521 view.update(cx, |view, cx| {
7522 view.select_line(&SelectLine, cx);
7523 assert_eq!(
7524 view.selected_display_ranges(cx),
7525 vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
7526 );
7527 });
7528 }
7529
7530 #[gpui::test]
7531 fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
7532 let settings = Settings::test(&cx);
7533 let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
7534 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7535 view.update(cx, |view, cx| {
7536 view.fold_ranges(
7537 vec![
7538 Point::new(0, 2)..Point::new(1, 2),
7539 Point::new(2, 3)..Point::new(4, 1),
7540 Point::new(7, 0)..Point::new(8, 4),
7541 ],
7542 cx,
7543 );
7544 view.select_display_ranges(
7545 &[
7546 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
7547 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7548 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
7549 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
7550 ],
7551 cx,
7552 );
7553 assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
7554 });
7555
7556 view.update(cx, |view, cx| {
7557 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7558 assert_eq!(
7559 view.display_text(cx),
7560 "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
7561 );
7562 assert_eq!(
7563 view.selected_display_ranges(cx),
7564 [
7565 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
7566 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
7567 DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
7568 DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
7569 ]
7570 );
7571 });
7572
7573 view.update(cx, |view, cx| {
7574 view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
7575 view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
7576 assert_eq!(
7577 view.display_text(cx),
7578 "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
7579 );
7580 assert_eq!(
7581 view.selected_display_ranges(cx),
7582 [
7583 DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
7584 DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
7585 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
7586 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
7587 DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
7588 DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
7589 DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
7590 DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
7591 ]
7592 );
7593 });
7594 }
7595
7596 #[gpui::test]
7597 fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
7598 let settings = Settings::test(&cx);
7599 let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
7600 let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
7601
7602 view.update(cx, |view, cx| {
7603 view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
7604 });
7605 view.update(cx, |view, cx| {
7606 view.add_selection_above(&AddSelectionAbove, cx);
7607 assert_eq!(
7608 view.selected_display_ranges(cx),
7609 vec![
7610 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7611 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7612 ]
7613 );
7614 });
7615
7616 view.update(cx, |view, cx| {
7617 view.add_selection_above(&AddSelectionAbove, cx);
7618 assert_eq!(
7619 view.selected_display_ranges(cx),
7620 vec![
7621 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
7622 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
7623 ]
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![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
7632 );
7633 });
7634
7635 view.update(cx, |view, cx| {
7636 view.add_selection_below(&AddSelectionBelow, cx);
7637 assert_eq!(
7638 view.selected_display_ranges(cx),
7639 vec![
7640 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7641 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7642 ]
7643 );
7644 });
7645
7646 view.update(cx, |view, cx| {
7647 view.add_selection_below(&AddSelectionBelow, cx);
7648 assert_eq!(
7649 view.selected_display_ranges(cx),
7650 vec![
7651 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
7652 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
7653 ]
7654 );
7655 });
7656
7657 view.update(cx, |view, cx| {
7658 view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
7659 });
7660 view.update(cx, |view, cx| {
7661 view.add_selection_below(&AddSelectionBelow, cx);
7662 assert_eq!(
7663 view.selected_display_ranges(cx),
7664 vec![
7665 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7666 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7667 ]
7668 );
7669 });
7670
7671 view.update(cx, |view, cx| {
7672 view.add_selection_below(&AddSelectionBelow, cx);
7673 assert_eq!(
7674 view.selected_display_ranges(cx),
7675 vec![
7676 DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
7677 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
7678 ]
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.add_selection_above(&AddSelectionAbove, cx);
7692 assert_eq!(
7693 view.selected_display_ranges(cx),
7694 vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
7695 );
7696 });
7697
7698 view.update(cx, |view, cx| {
7699 view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
7700 view.add_selection_below(&AddSelectionBelow, cx);
7701 assert_eq!(
7702 view.selected_display_ranges(cx),
7703 vec![
7704 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7705 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7706 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7707 ]
7708 );
7709 });
7710
7711 view.update(cx, |view, cx| {
7712 view.add_selection_below(&AddSelectionBelow, cx);
7713 assert_eq!(
7714 view.selected_display_ranges(cx),
7715 vec![
7716 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7717 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7718 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7719 DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
7720 ]
7721 );
7722 });
7723
7724 view.update(cx, |view, cx| {
7725 view.add_selection_above(&AddSelectionAbove, cx);
7726 assert_eq!(
7727 view.selected_display_ranges(cx),
7728 vec![
7729 DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
7730 DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
7731 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
7732 ]
7733 );
7734 });
7735
7736 view.update(cx, |view, cx| {
7737 view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
7738 });
7739 view.update(cx, |view, cx| {
7740 view.add_selection_above(&AddSelectionAbove, cx);
7741 assert_eq!(
7742 view.selected_display_ranges(cx),
7743 vec![
7744 DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
7745 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7746 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7747 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7748 ]
7749 );
7750 });
7751
7752 view.update(cx, |view, cx| {
7753 view.add_selection_below(&AddSelectionBelow, cx);
7754 assert_eq!(
7755 view.selected_display_ranges(cx),
7756 vec![
7757 DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
7758 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
7759 DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
7760 ]
7761 );
7762 });
7763 }
7764
7765 #[gpui::test]
7766 async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
7767 let settings = cx.read(Settings::test);
7768 let language = Arc::new(Language::new(
7769 LanguageConfig::default(),
7770 Some(tree_sitter_rust::language()),
7771 ));
7772
7773 let text = r#"
7774 use mod1::mod2::{mod3, mod4};
7775
7776 fn fn_1(param1: bool, param2: &str) {
7777 let var1 = "text";
7778 }
7779 "#
7780 .unindent();
7781
7782 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7783 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7784 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7785 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7786 .await;
7787
7788 view.update(&mut cx, |view, cx| {
7789 view.select_display_ranges(
7790 &[
7791 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7792 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7793 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7794 ],
7795 cx,
7796 );
7797 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7798 });
7799 assert_eq!(
7800 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7801 &[
7802 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7803 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7804 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7805 ]
7806 );
7807
7808 view.update(&mut cx, |view, cx| {
7809 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7810 });
7811 assert_eq!(
7812 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7813 &[
7814 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7815 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7816 ]
7817 );
7818
7819 view.update(&mut cx, |view, cx| {
7820 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7821 });
7822 assert_eq!(
7823 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7824 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7825 );
7826
7827 // Trying to expand the selected syntax node one more time has no effect.
7828 view.update(&mut cx, |view, cx| {
7829 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7830 });
7831 assert_eq!(
7832 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7833 &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
7834 );
7835
7836 view.update(&mut cx, |view, cx| {
7837 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7838 });
7839 assert_eq!(
7840 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7841 &[
7842 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7843 DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
7844 ]
7845 );
7846
7847 view.update(&mut cx, |view, cx| {
7848 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7849 });
7850 assert_eq!(
7851 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7852 &[
7853 DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
7854 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7855 DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
7856 ]
7857 );
7858
7859 view.update(&mut cx, |view, cx| {
7860 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7861 });
7862 assert_eq!(
7863 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7864 &[
7865 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7866 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7867 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7868 ]
7869 );
7870
7871 // Trying to shrink the selected syntax node one more time has no effect.
7872 view.update(&mut cx, |view, cx| {
7873 view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
7874 });
7875 assert_eq!(
7876 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7877 &[
7878 DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
7879 DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
7880 DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
7881 ]
7882 );
7883
7884 // Ensure that we keep expanding the selection if the larger selection starts or ends within
7885 // a fold.
7886 view.update(&mut cx, |view, cx| {
7887 view.fold_ranges(
7888 vec![
7889 Point::new(0, 21)..Point::new(0, 24),
7890 Point::new(3, 20)..Point::new(3, 22),
7891 ],
7892 cx,
7893 );
7894 view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
7895 });
7896 assert_eq!(
7897 view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
7898 &[
7899 DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
7900 DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
7901 DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
7902 ]
7903 );
7904 }
7905
7906 #[gpui::test]
7907 async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
7908 let settings = cx.read(Settings::test);
7909 let language = Arc::new(
7910 Language::new(
7911 LanguageConfig {
7912 brackets: vec![
7913 BracketPair {
7914 start: "{".to_string(),
7915 end: "}".to_string(),
7916 close: false,
7917 newline: true,
7918 },
7919 BracketPair {
7920 start: "(".to_string(),
7921 end: ")".to_string(),
7922 close: false,
7923 newline: true,
7924 },
7925 ],
7926 ..Default::default()
7927 },
7928 Some(tree_sitter_rust::language()),
7929 )
7930 .with_indents_query(
7931 r#"
7932 (_ "(" ")" @end) @indent
7933 (_ "{" "}" @end) @indent
7934 "#,
7935 )
7936 .unwrap(),
7937 );
7938
7939 let text = "fn a() {}";
7940
7941 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7942 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7943 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7944 editor
7945 .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
7946 .await;
7947
7948 editor.update(&mut cx, |editor, cx| {
7949 editor.select_ranges([5..5, 8..8, 9..9], None, cx);
7950 editor.newline(&Newline, cx);
7951 assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
7952 assert_eq!(
7953 editor.selected_ranges(cx),
7954 &[
7955 Point::new(1, 4)..Point::new(1, 4),
7956 Point::new(3, 4)..Point::new(3, 4),
7957 Point::new(5, 0)..Point::new(5, 0)
7958 ]
7959 );
7960 });
7961 }
7962
7963 #[gpui::test]
7964 async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
7965 let settings = cx.read(Settings::test);
7966 let language = Arc::new(Language::new(
7967 LanguageConfig {
7968 brackets: vec![
7969 BracketPair {
7970 start: "{".to_string(),
7971 end: "}".to_string(),
7972 close: true,
7973 newline: true,
7974 },
7975 BracketPair {
7976 start: "/*".to_string(),
7977 end: " */".to_string(),
7978 close: true,
7979 newline: true,
7980 },
7981 ],
7982 ..Default::default()
7983 },
7984 Some(tree_sitter_rust::language()),
7985 ));
7986
7987 let text = r#"
7988 a
7989
7990 /
7991
7992 "#
7993 .unindent();
7994
7995 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
7996 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
7997 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
7998 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
7999 .await;
8000
8001 view.update(&mut cx, |view, cx| {
8002 view.select_display_ranges(
8003 &[
8004 DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
8005 DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
8006 ],
8007 cx,
8008 );
8009 view.handle_input(&Input("{".to_string()), cx);
8010 view.handle_input(&Input("{".to_string()), cx);
8011 view.handle_input(&Input("{".to_string()), cx);
8012 assert_eq!(
8013 view.text(cx),
8014 "
8015 {{{}}}
8016 {{{}}}
8017 /
8018
8019 "
8020 .unindent()
8021 );
8022
8023 view.move_right(&MoveRight, cx);
8024 view.handle_input(&Input("}".to_string()), cx);
8025 view.handle_input(&Input("}".to_string()), cx);
8026 view.handle_input(&Input("}".to_string()), cx);
8027 assert_eq!(
8028 view.text(cx),
8029 "
8030 {{{}}}}
8031 {{{}}}}
8032 /
8033
8034 "
8035 .unindent()
8036 );
8037
8038 view.undo(&Undo, cx);
8039 view.handle_input(&Input("/".to_string()), cx);
8040 view.handle_input(&Input("*".to_string()), cx);
8041 assert_eq!(
8042 view.text(cx),
8043 "
8044 /* */
8045 /* */
8046 /
8047
8048 "
8049 .unindent()
8050 );
8051
8052 view.undo(&Undo, cx);
8053 view.select_display_ranges(
8054 &[
8055 DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
8056 DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
8057 ],
8058 cx,
8059 );
8060 view.handle_input(&Input("*".to_string()), cx);
8061 assert_eq!(
8062 view.text(cx),
8063 "
8064 a
8065
8066 /*
8067 *
8068 "
8069 .unindent()
8070 );
8071 });
8072 }
8073
8074 #[gpui::test]
8075 async fn test_snippets(mut cx: gpui::TestAppContext) {
8076 let settings = cx.read(Settings::test);
8077
8078 let text = "
8079 a. b
8080 a. b
8081 a. b
8082 "
8083 .unindent();
8084 let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
8085 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8086
8087 editor.update(&mut cx, |editor, cx| {
8088 let buffer = &editor.snapshot(cx).buffer_snapshot;
8089 let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
8090 let insertion_ranges = [
8091 Point::new(0, 2).to_offset(buffer)..Point::new(0, 2).to_offset(buffer),
8092 Point::new(1, 2).to_offset(buffer)..Point::new(1, 2).to_offset(buffer),
8093 Point::new(2, 2).to_offset(buffer)..Point::new(2, 2).to_offset(buffer),
8094 ];
8095
8096 editor
8097 .insert_snippet(&insertion_ranges, snippet, cx)
8098 .unwrap();
8099 assert_eq!(
8100 editor.text(cx),
8101 "
8102 a.f(one, two, three) b
8103 a.f(one, two, three) b
8104 a.f(one, two, three) b
8105 "
8106 .unindent()
8107 );
8108 assert_eq!(
8109 editor.selected_ranges::<Point>(cx),
8110 &[
8111 Point::new(0, 4)..Point::new(0, 7),
8112 Point::new(0, 14)..Point::new(0, 19),
8113 Point::new(1, 4)..Point::new(1, 7),
8114 Point::new(1, 14)..Point::new(1, 19),
8115 Point::new(2, 4)..Point::new(2, 7),
8116 Point::new(2, 14)..Point::new(2, 19),
8117 ]
8118 );
8119
8120 // Can't move earlier than the first tab stop
8121 editor.move_to_prev_snippet_tabstop(cx);
8122 assert_eq!(
8123 editor.selected_ranges::<Point>(cx),
8124 &[
8125 Point::new(0, 4)..Point::new(0, 7),
8126 Point::new(0, 14)..Point::new(0, 19),
8127 Point::new(1, 4)..Point::new(1, 7),
8128 Point::new(1, 14)..Point::new(1, 19),
8129 Point::new(2, 4)..Point::new(2, 7),
8130 Point::new(2, 14)..Point::new(2, 19),
8131 ]
8132 );
8133
8134 assert!(editor.move_to_next_snippet_tabstop(cx));
8135 assert_eq!(
8136 editor.selected_ranges::<Point>(cx),
8137 &[
8138 Point::new(0, 9)..Point::new(0, 12),
8139 Point::new(1, 9)..Point::new(1, 12),
8140 Point::new(2, 9)..Point::new(2, 12)
8141 ]
8142 );
8143
8144 editor.move_to_prev_snippet_tabstop(cx);
8145 assert_eq!(
8146 editor.selected_ranges::<Point>(cx),
8147 &[
8148 Point::new(0, 4)..Point::new(0, 7),
8149 Point::new(0, 14)..Point::new(0, 19),
8150 Point::new(1, 4)..Point::new(1, 7),
8151 Point::new(1, 14)..Point::new(1, 19),
8152 Point::new(2, 4)..Point::new(2, 7),
8153 Point::new(2, 14)..Point::new(2, 19),
8154 ]
8155 );
8156
8157 assert!(editor.move_to_next_snippet_tabstop(cx));
8158 assert!(editor.move_to_next_snippet_tabstop(cx));
8159 assert_eq!(
8160 editor.selected_ranges::<Point>(cx),
8161 &[
8162 Point::new(0, 20)..Point::new(0, 20),
8163 Point::new(1, 20)..Point::new(1, 20),
8164 Point::new(2, 20)..Point::new(2, 20)
8165 ]
8166 );
8167
8168 // As soon as the last tab stop is reached, snippet state is gone
8169 editor.move_to_prev_snippet_tabstop(cx);
8170 assert_eq!(
8171 editor.selected_ranges::<Point>(cx),
8172 &[
8173 Point::new(0, 20)..Point::new(0, 20),
8174 Point::new(1, 20)..Point::new(1, 20),
8175 Point::new(2, 20)..Point::new(2, 20)
8176 ]
8177 );
8178 });
8179 }
8180
8181 #[gpui::test]
8182 async fn test_completion(mut cx: gpui::TestAppContext) {
8183 let settings = cx.read(Settings::test);
8184 let (language_server, mut fake) = cx.update(|cx| {
8185 lsp::LanguageServer::fake_with_capabilities(
8186 lsp::ServerCapabilities {
8187 completion_provider: Some(lsp::CompletionOptions {
8188 trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
8189 ..Default::default()
8190 }),
8191 ..Default::default()
8192 },
8193 cx,
8194 )
8195 });
8196
8197 let text = "
8198 one
8199 two
8200 three
8201 "
8202 .unindent();
8203
8204 let fs = FakeFs::new(cx.background().clone());
8205 fs.insert_file("/file", text).await;
8206
8207 let project = Project::test(fs, &mut cx);
8208
8209 let (worktree, relative_path) = project
8210 .update(&mut cx, |project, cx| {
8211 project.find_or_create_local_worktree("/file", false, cx)
8212 })
8213 .await
8214 .unwrap();
8215 let project_path = ProjectPath {
8216 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
8217 path: relative_path.into(),
8218 };
8219 let buffer = project
8220 .update(&mut cx, |project, cx| project.open_buffer(project_path, cx))
8221 .await
8222 .unwrap();
8223 buffer.update(&mut cx, |buffer, cx| {
8224 buffer.set_language_server(Some(language_server), cx);
8225 });
8226
8227 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8228 buffer.next_notification(&cx).await;
8229
8230 let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8231
8232 editor.update(&mut cx, |editor, cx| {
8233 editor.project = Some(project);
8234 editor.select_ranges([Point::new(0, 3)..Point::new(0, 3)], None, cx);
8235 editor.handle_input(&Input(".".to_string()), cx);
8236 });
8237
8238 handle_completion_request(
8239 &mut fake,
8240 "/file",
8241 Point::new(0, 4),
8242 vec![
8243 (Point::new(0, 4)..Point::new(0, 4), "first_completion"),
8244 (Point::new(0, 4)..Point::new(0, 4), "second_completion"),
8245 ],
8246 )
8247 .await;
8248 editor
8249 .condition(&cx, |editor, _| editor.context_menu_visible())
8250 .await;
8251
8252 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
8253 editor.move_down(&MoveDown, cx);
8254 let apply_additional_edits = editor
8255 .confirm_completion(&ConfirmCompletion(None), cx)
8256 .unwrap();
8257 assert_eq!(
8258 editor.text(cx),
8259 "
8260 one.second_completion
8261 two
8262 three
8263 "
8264 .unindent()
8265 );
8266 apply_additional_edits
8267 });
8268
8269 handle_resolve_completion_request(
8270 &mut fake,
8271 Some((Point::new(2, 5)..Point::new(2, 5), "\nadditional edit")),
8272 )
8273 .await;
8274 apply_additional_edits.await.unwrap();
8275 assert_eq!(
8276 editor.read_with(&cx, |editor, cx| editor.text(cx)),
8277 "
8278 one.second_completion
8279 two
8280 three
8281 additional edit
8282 "
8283 .unindent()
8284 );
8285
8286 editor.update(&mut cx, |editor, cx| {
8287 editor.select_ranges(
8288 [
8289 Point::new(1, 3)..Point::new(1, 3),
8290 Point::new(2, 5)..Point::new(2, 5),
8291 ],
8292 None,
8293 cx,
8294 );
8295
8296 editor.handle_input(&Input(" ".to_string()), cx);
8297 assert!(editor.context_menu.is_none());
8298 editor.handle_input(&Input("s".to_string()), cx);
8299 assert!(editor.context_menu.is_none());
8300 });
8301
8302 handle_completion_request(
8303 &mut fake,
8304 "/file",
8305 Point::new(2, 7),
8306 vec![
8307 (Point::new(2, 6)..Point::new(2, 7), "fourth_completion"),
8308 (Point::new(2, 6)..Point::new(2, 7), "fifth_completion"),
8309 (Point::new(2, 6)..Point::new(2, 7), "sixth_completion"),
8310 ],
8311 )
8312 .await;
8313 editor
8314 .condition(&cx, |editor, _| editor.context_menu_visible())
8315 .await;
8316
8317 editor.update(&mut cx, |editor, cx| {
8318 editor.handle_input(&Input("i".to_string()), cx);
8319 });
8320
8321 handle_completion_request(
8322 &mut fake,
8323 "/file",
8324 Point::new(2, 8),
8325 vec![
8326 (Point::new(2, 6)..Point::new(2, 8), "fourth_completion"),
8327 (Point::new(2, 6)..Point::new(2, 8), "fifth_completion"),
8328 (Point::new(2, 6)..Point::new(2, 8), "sixth_completion"),
8329 ],
8330 )
8331 .await;
8332 editor
8333 .condition(&cx, |editor, _| editor.context_menu_visible())
8334 .await;
8335
8336 let apply_additional_edits = editor.update(&mut cx, |editor, cx| {
8337 let apply_additional_edits = editor
8338 .confirm_completion(&ConfirmCompletion(None), cx)
8339 .unwrap();
8340 assert_eq!(
8341 editor.text(cx),
8342 "
8343 one.second_completion
8344 two sixth_completion
8345 three sixth_completion
8346 additional edit
8347 "
8348 .unindent()
8349 );
8350 apply_additional_edits
8351 });
8352 handle_resolve_completion_request(&mut fake, None).await;
8353 apply_additional_edits.await.unwrap();
8354
8355 async fn handle_completion_request(
8356 fake: &mut FakeLanguageServer,
8357 path: &'static str,
8358 position: Point,
8359 completions: Vec<(Range<Point>, &'static str)>,
8360 ) {
8361 fake.handle_request::<lsp::request::Completion, _>(move |params, _| {
8362 assert_eq!(
8363 params.text_document_position.text_document.uri,
8364 lsp::Url::from_file_path(path).unwrap()
8365 );
8366 assert_eq!(
8367 params.text_document_position.position,
8368 lsp::Position::new(position.row, position.column)
8369 );
8370 Some(lsp::CompletionResponse::Array(
8371 completions
8372 .iter()
8373 .map(|(range, new_text)| lsp::CompletionItem {
8374 label: new_text.to_string(),
8375 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
8376 range: lsp::Range::new(
8377 lsp::Position::new(range.start.row, range.start.column),
8378 lsp::Position::new(range.start.row, range.start.column),
8379 ),
8380 new_text: new_text.to_string(),
8381 })),
8382 ..Default::default()
8383 })
8384 .collect(),
8385 ))
8386 })
8387 .next()
8388 .await;
8389 }
8390
8391 async fn handle_resolve_completion_request(
8392 fake: &mut FakeLanguageServer,
8393 edit: Option<(Range<Point>, &'static str)>,
8394 ) {
8395 fake.handle_request::<lsp::request::ResolveCompletionItem, _>(move |_, _| {
8396 lsp::CompletionItem {
8397 additional_text_edits: edit.clone().map(|(range, new_text)| {
8398 vec![lsp::TextEdit::new(
8399 lsp::Range::new(
8400 lsp::Position::new(range.start.row, range.start.column),
8401 lsp::Position::new(range.end.row, range.end.column),
8402 ),
8403 new_text.to_string(),
8404 )]
8405 }),
8406 ..Default::default()
8407 }
8408 })
8409 .next()
8410 .await;
8411 }
8412 }
8413
8414 #[gpui::test]
8415 async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
8416 let settings = cx.read(Settings::test);
8417 let language = Arc::new(Language::new(
8418 LanguageConfig {
8419 line_comment: Some("// ".to_string()),
8420 ..Default::default()
8421 },
8422 Some(tree_sitter_rust::language()),
8423 ));
8424
8425 let text = "
8426 fn a() {
8427 //b();
8428 // c();
8429 // d();
8430 }
8431 "
8432 .unindent();
8433
8434 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8435 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8436 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8437
8438 view.update(&mut cx, |editor, cx| {
8439 // If multiple selections intersect a line, the line is only
8440 // toggled once.
8441 editor.select_display_ranges(
8442 &[
8443 DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
8444 DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
8445 ],
8446 cx,
8447 );
8448 editor.toggle_comments(&ToggleComments, cx);
8449 assert_eq!(
8450 editor.text(cx),
8451 "
8452 fn a() {
8453 b();
8454 c();
8455 d();
8456 }
8457 "
8458 .unindent()
8459 );
8460
8461 // The comment prefix is inserted at the same column for every line
8462 // in a selection.
8463 editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
8464 editor.toggle_comments(&ToggleComments, cx);
8465 assert_eq!(
8466 editor.text(cx),
8467 "
8468 fn a() {
8469 // b();
8470 // c();
8471 // d();
8472 }
8473 "
8474 .unindent()
8475 );
8476
8477 // If a selection ends at the beginning of a line, that line is not toggled.
8478 editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
8479 editor.toggle_comments(&ToggleComments, cx);
8480 assert_eq!(
8481 editor.text(cx),
8482 "
8483 fn a() {
8484 // b();
8485 c();
8486 // d();
8487 }
8488 "
8489 .unindent()
8490 );
8491 });
8492 }
8493
8494 #[gpui::test]
8495 fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
8496 let settings = Settings::test(cx);
8497 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8498 let multibuffer = cx.add_model(|cx| {
8499 let mut multibuffer = MultiBuffer::new(0);
8500 multibuffer.push_excerpts(
8501 buffer.clone(),
8502 [
8503 Point::new(0, 0)..Point::new(0, 4),
8504 Point::new(1, 0)..Point::new(1, 4),
8505 ],
8506 cx,
8507 );
8508 multibuffer
8509 });
8510
8511 assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
8512
8513 let (_, view) = cx.add_window(Default::default(), |cx| {
8514 build_editor(multibuffer, settings, cx)
8515 });
8516 view.update(cx, |view, cx| {
8517 assert_eq!(view.text(cx), "aaaa\nbbbb");
8518 view.select_ranges(
8519 [
8520 Point::new(0, 0)..Point::new(0, 0),
8521 Point::new(1, 0)..Point::new(1, 0),
8522 ],
8523 None,
8524 cx,
8525 );
8526
8527 view.handle_input(&Input("X".to_string()), cx);
8528 assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
8529 assert_eq!(
8530 view.selected_ranges(cx),
8531 [
8532 Point::new(0, 1)..Point::new(0, 1),
8533 Point::new(1, 1)..Point::new(1, 1),
8534 ]
8535 )
8536 });
8537 }
8538
8539 #[gpui::test]
8540 fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
8541 let settings = Settings::test(cx);
8542 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8543 let multibuffer = cx.add_model(|cx| {
8544 let mut multibuffer = MultiBuffer::new(0);
8545 multibuffer.push_excerpts(
8546 buffer,
8547 [
8548 Point::new(0, 0)..Point::new(1, 4),
8549 Point::new(1, 0)..Point::new(2, 4),
8550 ],
8551 cx,
8552 );
8553 multibuffer
8554 });
8555
8556 assert_eq!(
8557 multibuffer.read(cx).read(cx).text(),
8558 "aaaa\nbbbb\nbbbb\ncccc"
8559 );
8560
8561 let (_, view) = cx.add_window(Default::default(), |cx| {
8562 build_editor(multibuffer, settings, cx)
8563 });
8564 view.update(cx, |view, cx| {
8565 view.select_ranges(
8566 [
8567 Point::new(1, 1)..Point::new(1, 1),
8568 Point::new(2, 3)..Point::new(2, 3),
8569 ],
8570 None,
8571 cx,
8572 );
8573
8574 view.handle_input(&Input("X".to_string()), cx);
8575 assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
8576 assert_eq!(
8577 view.selected_ranges(cx),
8578 [
8579 Point::new(1, 2)..Point::new(1, 2),
8580 Point::new(2, 5)..Point::new(2, 5),
8581 ]
8582 );
8583
8584 view.newline(&Newline, cx);
8585 assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
8586 assert_eq!(
8587 view.selected_ranges(cx),
8588 [
8589 Point::new(2, 0)..Point::new(2, 0),
8590 Point::new(6, 0)..Point::new(6, 0),
8591 ]
8592 );
8593 });
8594 }
8595
8596 #[gpui::test]
8597 fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
8598 let settings = Settings::test(cx);
8599 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
8600 let mut excerpt1_id = None;
8601 let multibuffer = cx.add_model(|cx| {
8602 let mut multibuffer = MultiBuffer::new(0);
8603 excerpt1_id = multibuffer
8604 .push_excerpts(
8605 buffer.clone(),
8606 [
8607 Point::new(0, 0)..Point::new(1, 4),
8608 Point::new(1, 0)..Point::new(2, 4),
8609 ],
8610 cx,
8611 )
8612 .into_iter()
8613 .next();
8614 multibuffer
8615 });
8616 assert_eq!(
8617 multibuffer.read(cx).read(cx).text(),
8618 "aaaa\nbbbb\nbbbb\ncccc"
8619 );
8620 let (_, editor) = cx.add_window(Default::default(), |cx| {
8621 let mut editor = build_editor(multibuffer.clone(), settings, cx);
8622 editor.select_ranges(
8623 [
8624 Point::new(1, 3)..Point::new(1, 3),
8625 Point::new(2, 1)..Point::new(2, 1),
8626 ],
8627 None,
8628 cx,
8629 );
8630 editor
8631 });
8632
8633 // Refreshing selections is a no-op when excerpts haven't changed.
8634 editor.update(cx, |editor, cx| {
8635 editor.refresh_selections(cx);
8636 assert_eq!(
8637 editor.selected_ranges(cx),
8638 [
8639 Point::new(1, 3)..Point::new(1, 3),
8640 Point::new(2, 1)..Point::new(2, 1),
8641 ]
8642 );
8643 });
8644
8645 multibuffer.update(cx, |multibuffer, cx| {
8646 multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
8647 });
8648 editor.update(cx, |editor, cx| {
8649 // Removing an excerpt causes the first selection to become degenerate.
8650 assert_eq!(
8651 editor.selected_ranges(cx),
8652 [
8653 Point::new(0, 0)..Point::new(0, 0),
8654 Point::new(0, 1)..Point::new(0, 1)
8655 ]
8656 );
8657
8658 // Refreshing selections will relocate the first selection to the original buffer
8659 // location.
8660 editor.refresh_selections(cx);
8661 assert_eq!(
8662 editor.selected_ranges(cx),
8663 [
8664 Point::new(0, 1)..Point::new(0, 1),
8665 Point::new(0, 3)..Point::new(0, 3)
8666 ]
8667 );
8668 });
8669 }
8670
8671 #[gpui::test]
8672 async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
8673 let settings = cx.read(Settings::test);
8674 let language = Arc::new(Language::new(
8675 LanguageConfig {
8676 brackets: vec![
8677 BracketPair {
8678 start: "{".to_string(),
8679 end: "}".to_string(),
8680 close: true,
8681 newline: true,
8682 },
8683 BracketPair {
8684 start: "/* ".to_string(),
8685 end: " */".to_string(),
8686 close: true,
8687 newline: true,
8688 },
8689 ],
8690 ..Default::default()
8691 },
8692 Some(tree_sitter_rust::language()),
8693 ));
8694
8695 let text = concat!(
8696 "{ }\n", // Suppress rustfmt
8697 " x\n", //
8698 " /* */\n", //
8699 "x\n", //
8700 "{{} }\n", //
8701 );
8702
8703 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
8704 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
8705 let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
8706 view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
8707 .await;
8708
8709 view.update(&mut cx, |view, cx| {
8710 view.select_display_ranges(
8711 &[
8712 DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
8713 DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
8714 DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
8715 ],
8716 cx,
8717 );
8718 view.newline(&Newline, cx);
8719
8720 assert_eq!(
8721 view.buffer().read(cx).read(cx).text(),
8722 concat!(
8723 "{ \n", // Suppress rustfmt
8724 "\n", //
8725 "}\n", //
8726 " x\n", //
8727 " /* \n", //
8728 " \n", //
8729 " */\n", //
8730 "x\n", //
8731 "{{} \n", //
8732 "}\n", //
8733 )
8734 );
8735 });
8736 }
8737
8738 #[gpui::test]
8739 fn test_highlighted_ranges(cx: &mut gpui::MutableAppContext) {
8740 let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
8741 let settings = Settings::test(&cx);
8742 let (_, editor) = cx.add_window(Default::default(), |cx| {
8743 build_editor(buffer.clone(), settings, cx)
8744 });
8745
8746 editor.update(cx, |editor, cx| {
8747 struct Type1;
8748 struct Type2;
8749
8750 let buffer = buffer.read(cx).snapshot(cx);
8751
8752 let anchor_range = |range: Range<Point>| {
8753 buffer.anchor_after(range.start)..buffer.anchor_after(range.end)
8754 };
8755
8756 editor.highlight_ranges::<Type1>(
8757 vec![
8758 anchor_range(Point::new(2, 1)..Point::new(2, 3)),
8759 anchor_range(Point::new(4, 2)..Point::new(4, 4)),
8760 anchor_range(Point::new(6, 3)..Point::new(6, 5)),
8761 anchor_range(Point::new(8, 4)..Point::new(8, 6)),
8762 ],
8763 Color::red(),
8764 cx,
8765 );
8766 editor.highlight_ranges::<Type2>(
8767 vec![
8768 anchor_range(Point::new(3, 2)..Point::new(3, 5)),
8769 anchor_range(Point::new(5, 3)..Point::new(5, 6)),
8770 anchor_range(Point::new(7, 4)..Point::new(7, 7)),
8771 anchor_range(Point::new(9, 5)..Point::new(9, 8)),
8772 ],
8773 Color::green(),
8774 cx,
8775 );
8776
8777 let snapshot = editor.snapshot(cx);
8778 let mut highlighted_ranges = editor.highlighted_ranges_in_range(
8779 anchor_range(Point::new(3, 4)..Point::new(7, 4)),
8780 &snapshot,
8781 );
8782 // Enforce a consistent ordering based on color without relying on the ordering of the
8783 // highlight's `TypeId` which is non-deterministic.
8784 highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
8785 assert_eq!(
8786 highlighted_ranges,
8787 &[
8788 (
8789 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 5),
8790 Color::green(),
8791 ),
8792 (
8793 DisplayPoint::new(5, 3)..DisplayPoint::new(5, 6),
8794 Color::green(),
8795 ),
8796 (
8797 DisplayPoint::new(4, 2)..DisplayPoint::new(4, 4),
8798 Color::red(),
8799 ),
8800 (
8801 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8802 Color::red(),
8803 ),
8804 ]
8805 );
8806 assert_eq!(
8807 editor.highlighted_ranges_in_range(
8808 anchor_range(Point::new(5, 6)..Point::new(6, 4)),
8809 &snapshot,
8810 ),
8811 &[(
8812 DisplayPoint::new(6, 3)..DisplayPoint::new(6, 5),
8813 Color::red(),
8814 )]
8815 );
8816 });
8817 }
8818
8819 #[test]
8820 fn test_combine_syntax_and_fuzzy_match_highlights() {
8821 let string = "abcdefghijklmnop";
8822 let default = HighlightStyle::default();
8823 let syntax_ranges = [
8824 (
8825 0..3,
8826 HighlightStyle {
8827 color: Color::red(),
8828 ..default
8829 },
8830 ),
8831 (
8832 4..8,
8833 HighlightStyle {
8834 color: Color::green(),
8835 ..default
8836 },
8837 ),
8838 ];
8839 let match_indices = [4, 6, 7, 8];
8840 assert_eq!(
8841 combine_syntax_and_fuzzy_match_highlights(
8842 &string,
8843 default,
8844 syntax_ranges.into_iter(),
8845 &match_indices,
8846 ),
8847 &[
8848 (
8849 0..3,
8850 HighlightStyle {
8851 color: Color::red(),
8852 ..default
8853 },
8854 ),
8855 (
8856 4..5,
8857 HighlightStyle {
8858 color: Color::green(),
8859 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8860 ..default
8861 },
8862 ),
8863 (
8864 5..6,
8865 HighlightStyle {
8866 color: Color::green(),
8867 ..default
8868 },
8869 ),
8870 (
8871 6..8,
8872 HighlightStyle {
8873 color: Color::green(),
8874 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8875 ..default
8876 },
8877 ),
8878 (
8879 8..9,
8880 HighlightStyle {
8881 font_properties: *fonts::Properties::default().weight(fonts::Weight::BOLD),
8882 ..default
8883 },
8884 ),
8885 ]
8886 );
8887 }
8888
8889 fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
8890 let point = DisplayPoint::new(row as u32, column as u32);
8891 point..point
8892 }
8893
8894 fn build_editor(
8895 buffer: ModelHandle<MultiBuffer>,
8896 settings: Settings,
8897 cx: &mut ViewContext<Editor>,
8898 ) -> Editor {
8899 let settings = watch::channel_with(settings);
8900 Editor::new(EditorMode::Full, buffer, None, settings.1, None, cx)
8901 }
8902}
8903
8904trait RangeExt<T> {
8905 fn sorted(&self) -> Range<T>;
8906 fn to_inclusive(&self) -> RangeInclusive<T>;
8907}
8908
8909impl<T: Ord + Clone> RangeExt<T> for Range<T> {
8910 fn sorted(&self) -> Self {
8911 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
8912 }
8913
8914 fn to_inclusive(&self) -> RangeInclusive<T> {
8915 self.start.clone()..=self.end.clone()
8916 }
8917}