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